Invia messaggi WhatsApp da file CSV usando Node Js

4 luglio 2024

Vuoi rendere la comunicazione aziendale su WhatsApp più efficace? Questo tutorial ti mostrerà come inviare messaggi ai numeri di telefono memorizzati in un file CSV usando Node.js, la libreria Axios e le Wassenger API. Imparerai a leggere i numeri di telefono e i messaggi dal file CSV e a inviarli automaticamente con Wassenger.

Questo articolo ti dà una rapida panoramica delle funzionalità delle Wassenger API.

🫣 Non vuoi usare la programmazione? Nessun problema! Esplora la nostra nuova funzionalità di campagne WhatsApp no-code. Importa i tuoi contatti, definisci un messaggio, imposta una data di invio e rilassati! 🥳 🥳

Scopri altri casi d'uso ed esempi di codice pronti per vedere come puoi migliorare la tua strategia di marketing su WhatsApp.

Prerequisiti

🤩 🤖 Wassenger è una piattaforma di comunicazione completa e una soluzione API per WhatsApp. Esplora oltre 100+ casi d'uso API e automatizza qualsiasi cosa su WhatsApp iscrivendoti per una prova gratuita e inizia in pochi minuti**!**

Installa i pacchetti richiesti

Per prima cosa, crea una nuova directory per il tuo progetto e spostati in essa nel terminale. Poi esegui i seguenti comandi per creare un nuovo file package.json e installare le librerie necessarie:

npm init -y
npm install axios csv-parse

Crea il file CSV

Crea un nuovo file chiamato numbers.csv nella directory del progetto con due colonne:

  1. Prima colonna: numero di telefono in E164 format con il prefisso del paese.
  2. Seconda colonna: messaggio di testo da inviare al numero di destinazione.

Il foglio di calcolo dovrebbe avere questo aspetto:

Il documento equivalente esportato come CSV dovrebbe apparire così:

(+1234567890,
  '👋 Welcome to {{your-business-name}}! Thanks for signing up.We are just a message away!' +
    1234567890,
  "💐 Your order has been shipped.Tracking number is {{tracking-number}}.Don't hesitate to reach out to if you need help! 🤗");

Puoi esportare qualsiasi documento Office Excel o Google Sheets come file CSV seguendo queste istruzioni:

Crea un file con il codice

Inviare messaggi di testo

Crea un nuovo file chiamato send_messages.js nella directory del progetto e aggiungi il seguente codice:

const axios = require('axios');
const fs = require('fs/promises');
const { parse } = require('csv-parse/sync');
// Set local path of the CSV file
// You can export any Excel/Google Sheets document as CSV
const csvFile = 'file.csv';
// Replace this with your Wassenger API token
// Get your API token here: https://app.wassenger.com/apikeys
const token = 'ENTER API KEY HERE';
// Optionally specify the target WhatsApp device ID connected to Wassenger
// you want to use for messages delivery(24 characters hexadecimal value)
const device = 'DEVICE ID GOES HERE';
// Set the download URL of the file to be sent.
// The file must be publicly accessible from the Internet and return the file binary content
// You can also upload a local file in Google Drive and make the file publicly available for download
// Accepted file formats are: images(JPEG, WEBP, PNG), video(MP4), audio(MP3, OGG) and documents(PDF, XLSX, DOCX, ZIP...)
const fileUrl = 'https://picsum.photos/seed/picsum/600/500';
// Define the headers for the API request
const headers = {
  'Content-Type': 'application/json',
  Authorization: `${token}`
};
// Define the URL for the Wassenger API
const url = 'https://api.wassenger.com/v1/messages';
const normalizePhone = phone => {
  return `+${phone.replace(/\D/g, '')}`;
};
const sendMessage = async (phone, message) => {
  const body = { device, phone, message: message.trim() };
  try {
    const response = await axios.post(url, body, { headers });
    console.log(`=> Message created: ${phone}`);
  } catch (error) {
    console.error(
      'Failed to create message to ${phone}:',
      error.response ? error.response.data : error
    );
  }
};
const main = async () => {
  try {
    console.log('=> Reading CSV file...');
    const data = await fs.readFile(csvFile, 'utf-8');
    const records = parse(data, { columns: false, skip_empty_lines: true });
    console.log('=> Processing messages...');
    for (const [phone, message] of records) {
      if (!phone || !message) {
        continue;
      }
      const number = normalizePhone(phone);
      if (number && number.length >= 8 && message) {
        await sendMessage(number, message);
      }
    }
  } catch (err) {
    console.error('Error:', err);
  }
};
main();

🤩 🤖 Wassenger è una piattaforma di comunicazione completa e una soluzione API per WhatsApp. Esplora oltre 100+ casi d'uso API e automatizza qualsiasi cosa su WhatsApp iscrivendoti per una prova gratuita e inizia in pochi minuti**!**

Inviare messaggi multimediali

In questo esempio creeremo un programma diverso chiamato send_media.js per inviare messaggi multimediali (immagini) a più numeri di telefono caricati da un documento Google Sheets.

Il modo più semplice per inviare un messaggio multimediale è fornire un URL di download del file. Se il tuo file non è già caricato da qualche parte, puoi caricarlo su Google Drive e renderlo pubblicamente disponibile per permettere a Wassenger di scaricarlo e inviarlo.

Esempio di URL di download da un file pubblico in Google Drive:

https://drive.google.com/uc?id=1RG3CAPiwiFlFATUlIIwhk0RrbEU4PgVP&export=download

Importante: l'URL di download fornito deve restituire il contenuto binario del file, altrimenti l'operazione fallirà.

Crea un nuovo file chiamato send_media.js nella directory del progetto e aggiungi il seguente codice:

const axios = require('axios');
const { parse } = require('csv-parse/sync');
// Set local path of the CSV file
// You can export any Excel/Google Sheets document as CSV
const csvFile = 'file.csv';
// Set the download URL of the file to be sent.
// The file must be publicly accessible from the Internet and return the file binary content
// You can also upload a local file in Google Drive and make the file publicly available for download
// Accepted file formats are: images(JPEG, WEBP, PNG), video(MP4), audio(MP3, OGG) and documents(PDF, XLSX, DOCX, ZIP...)
const fileUrl = 'https://picsum.photos/seed/picsum/600/500';
// Replace this with your Wassenger API token
// Get your API token here: https://app.wassenger.com/apikeys
const token = 'ENTER API KEY HERE';
// Optionally specify the target WhatsApp device ID connected to Wassenger
// you want to use for messages delivery(24 characters hexadecimal value)
const device = 'DEVICE ID GOES HERE';
// Define the headers for the API request
const headers = {
  'Content-Type': 'application/json',
  Authorization: `${token}`
};
// Define URLs for the Wassenger API
const baseUrl = 'https://api.wassenger.com/v1';
const url = `${baseUrl}/messages`;
const filesUrl = `${baseUrl}/files`;
const uploadFile = async url => {
  const body = { url };
  try {
    const response = await axios.post(filesUrl, body, { headers });
    return response.data.id;
  } catch (error) {
    // If the file already exists, obtain the file ID from the response
    if (
      error.response &&
      error.response.status === 409 &&
      error.response.data
    ) {
      return error.response.data.meta.file;
    }
    console.error(
      'Failed to upload file:',
      error.response ? error.response.data : error
    );
  }
};
const normalizePhone = phone => {
  return `+${phone.replace(/\D/g, '')}`;
};
const sendMessage = async (phone, message, file) => {
  const body = {
    phone,
    message: message.trim(),
    device,
    media: { file }
  };
  try {
    await axios.post(url, body, { headers });
    console.log(` == > Message created: ${phone}`);
  } catch (error) {
    console.error(
      'Failed to create message to ${phone}:',
      error.response ? error.response.data : error
    );
  }
};
const main = async () => {
  try {
    if (!fileUrl) {
      throw new Error('Missing required fileUrl');
    }
    console.log('=> Reading CSV file...');
    const data = await fs.readFile(csvFile, 'utf-8');
    const records = parse(data, { columns: false, skip_empty_lines: true });
    console.log('=> Uploading file...');
    const file = await uploadFile(fileUrl);
    if (!file) {
      throw new Error('Failed to upload file: check the error');
    }
    console.log('=> Processing messages...');
    for (const [phone, message] of records) {
      if (!phone || !message) {
        continue;
      }
      const number = normalizePhone(phone);
      if (number && number.length >= 8 && message) {
        await sendMessage(number, message, file);
      }
    }
  } catch (err) {
    console.error('Error:', err);
  }
};
main();

Esegui e testa il codice nel cloud senza installare software sul tuo computer. Crea un account gratuito su Replit e inizia in pochi minuti

Sostituire il token API

Nel file send_messages.js, assicurati di aver definito il token API del tuo account Wassenger reale:

// Replace this with your Wassenger API token
const token = 'ENTER API KEY HERE';

Facoltativamente, se hai più numeri WhatsApp collegati al tuo account Wassenger, puoi specificare quale numero WhatsApp vuoi usare per la consegna dei messaggi indicando l'ID univoco del dispositivo Wassenger (valore esadecimale di 24 caratteri) nella seguente riga:

// Optionally specify the target WhatsApp device ID connected to Wassenger
// you want to use for messages delivery(24 characters hexadecimal value)
const device = 'DEVICE ID GOES HERE';

🤩 🤖 Wassenger è una piattaforma di comunicazione completa e una soluzione API per WhatsApp. Esplora oltre 100+ casi d'uso API e automatizza qualsiasi cosa su WhatsApp iscrivendoti per una prova gratuita e inizia in pochi minuti**!**

Esegui il programma

️➡️ Esegui il programma nel cloud ⬅️

const axios = require('axios');
const { parse } = require('csv-parse/sync');
// Set local path of the CSV file
// You can export any Excel/Google Sheets document as CSV
const csvFile = 'file.csv';
// Set the download URL of the file to be sent.
// The file must be publicly accessible from the Internet and return the file binary content
// You can also upload a local file in Google Drive and make the file publicly available for download
// Accepted file formats are: images(JPEG, WEBP, PNG), video(MP4), audio(MP3, OGG) and documents(PDF, XLSX, DOCX, ZIP...)
const fileUrl = 'https://picsum.photos/seed/picsum/600/500';
// Replace this with your Wassenger API token
// Get your API token here: https://app.wassenger.com/apikeys
const token = 'ENTER API KEY HERE';
// Optionally specify the target WhatsApp device ID connected to Wassenger
// you want to use for messages delivery(24 characters hexadecimal value)
const device = 'DEVICE ID GOES HERE';
// Define the headers for the API request
const headers = {
  'Content-Type': 'application/json',
  Authorization: `${token}`
};
// Define URLs for the Wassenger API
const baseUrl = 'https://api.wassenger.com/v1';
const url = `${baseUrl}/messages`;
const filesUrl = `${baseUrl}/files`;
const uploadFile = async url => {
  const body = { url };
  try {
    const response = await axios.post(filesUrl, body, { headers });
    return response.data.id;
  } catch (error) {
    // If the file already exists, obtain the file ID from the response
    if (
      error.response &&
      error.response.status === 409 &&
      error.response.data
    ) {
      return error.response.data.meta.file;
    }
    console.error(
      'Failed to upload file:',
      error.response ? error.response.data : error
    );
  }
};
const normalizePhone = phone => {
  return `+${phone.replace(/\D/g, '')}`;
};
const sendMessage = async (phone, message, file) => {
  const body = {
    phone,
    message: message.trim(),
    device,
    media: { file }
  };
  try {
    await axios.post(url, body, { headers });
    console.log(` == > Message created: ${phone}`);
  } catch (error) {
    console.error(
      'Failed to create message to ${phone}:',
      error.response ? error.response.data : error
    );
  }
};
const main = async () => {
  try {
    if (!fileUrl) {
      throw new Error('Missing required fileUrl');
    }
    console.log('=> Reading CSV file...');
    const data = await fs.readFile(csvFile, 'utf-8');
    const records = parse(data, { columns: false, skip_empty_lines: true });
    console.log('=> Uploading file...');
    const file = await uploadFile(fileUrl);
    if (!file) {
      throw new Error('Failed to upload file: check the error');
    }
    console.log('=> Processing messages...');
    for (const [phone, message] of records) {
      if (!phone || !message) {
        continue;
      }
      const number = normalizePhone(phone);
      if (number && number.length >= 8 && message) {
        await sendMessage(number, message, file);
      }
    }
  } catch (err) {
    console.error('Error:', err);
  }
};
main();

Esegui il programma sul tuo computer

Prima di eseguire il programma, se prevedi di inviare centinaia di messaggi consecutivi, consigliamo di impostare una velocità di consegna dei messaggi più bassa, non più di 2–3 messaggi al minuto per prevenire problemi di ban dovuti alle politiche anti-spam di WhatsApp. Scopri di più sulle migliori pratiche e su come ridurre i rischi qui.

Apri un terminale nella directory del progetto ed esegui il comando seguente per eseguire lo script send_messages.js:

node send_messages.js

Analogamente, puoi eseguire lo script send_media.js per inviare messaggi multimediali:

node send_media.js

Se tutto è configurato correttamente, dovresti vedere un output che indica che i messaggi sono stati creati con successo:

=> Message created: +1234567890
=> Message created: +1234567890
=> Message created: +1234567890

Nota: i messaggi verranno aggiunti alla coda di consegna del tuo numero e inviati in modo asincrono in background nel tempo, in base al limite di velocità di consegna dei messaggi per minuto della tua sottoscrizione o alla velocità di consegna configurata manualmente nelle impostazioni del tuo numero.

I messaggi potrebbero impiegare diversi minuti o ore, a seconda della quantità di messaggi creati, per essere effettivamente recapitati ai numeri di telefono di destinazione tramite WhatsApp. Puoi monitorare l'avanzamento della consegna dei messaggi nel pannello web o automaticamente usando gli eventi webhook.

Conclusione

In questo tutorial hai imparato come inviare messaggi ai numeri di telefono memorizzati in un file CSV usando Node.js, la libreria axios e le API di Wassenger.

Puoi aggiornare il file numbers.csv ed eseguire il programma ogni volta che desideri inviare nuovi messaggi tramite il tuo numero WhatsApp connesso a Wassenger.

Puoi ulteriormente personalizzare lo script per gestire colonne aggiuntive, creare diversi tipi di messaggi o integrarlo con il tuo software secondo le tue esigenze.

🤩 🤖 Wassenger è una piattaforma di comunicazione completa e una soluzione API per WhatsApp. Esplora oltre 100+ casi d'uso API e automatizza qualsiasi cosa su WhatsApp iscrivendoti per una prova gratuita e inizia in pochi minuti**!**

Ready to transform your WhatsApp communication?

Start automating your customer interactions today with Wassenger

Get Started Free