WhatsApp-Nachrichten aus CSV-Dateien mit Node Js senden

4. Juli 2024

Möchten Sie Ihre geschäftliche Kommunikation über WhatsApp effektiver gestalten? Dieses Tutorial zeigt Ihnen, wie Sie Nachrichten an Telefonnummern senden, die in einer CSV-Datei gespeichert sind, mithilfe von Node.js, der Axios-Bibliothek und der Wassenger API. Sie lernen, Telefonnummern und Nachrichten aus der CSV-Datei zu lesen und diese automatisch mit Wassenger zu versenden.

Dieser Artikel gibt Ihnen einen schnellen Einblick in die Funktionen der Wassenger API.

🫣 Keine Lust zu programmieren? Kein Problem! Probieren Sie unsere neue No-Code WhatsApp-Kampagnen-Funktion aus. Importieren Sie Ihre Kontakte, definieren Sie eine Nachricht, legen Sie ein Zustelldatum fest und lehnen Sie sich zurück! 🥳 🥳

Sehen Sie sich weitere Anwendungsfälle und fertige Codebeispiele an, um zu sehen, wie Sie Ihre WhatsApp-Marketingstrategie verbessern können.

Voraussetzungen

🤩 🤖 Wassenger ist eine vollständige Kommunikationsplattform und API-Lösung für WhatsApp. Entdecken Sie mehr als 100+ API-Anwendungsfälle und automatisieren Sie alles auf WhatsApp, indem Sie sich für eine kostenlose Testversion anmelden und in wenigen Minuten loslegen!

Erforderliche Pakete installieren

Erstellen Sie zuerst ein neues Verzeichnis für Ihr Projekt und navigieren Sie in Ihrem Terminal dorthin. Führen Sie dann die folgenden Befehle aus, um eine neue package.json-Datei zu erstellen und die notwendigen Bibliotheken zu installieren:

npm init -y
npm install axios csv-parse

Erstellen der CSV-Datei

Erstellen Sie eine neue Datei mit dem Namen numbers.csv in Ihrem Projektverzeichnis mit zwei Spalten:

  1. Erste Spalte: Telefonnummer im E.164-Format mit Landesvorwahl.
  2. Zweite Spalte: Textnachricht, die an die Zieltelefonnummer gesendet werden soll.

Das Tabellenblatt sollte so aussehen:

Das entsprechende als CSV exportierte Tabellenblatt sollte wie folgt aussehen:

(+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! 🤗");

Sie können jedes Office-Excel- oder Google-Sheets-Dokument als CSV-Datei exportieren, indem Sie diesen Anleitungen folgen:

Erstellen Sie eine Datei mit dem Code

Textnachrichten senden

Erstellen Sie eine neue Datei mit dem Namen send_messages.js in Ihrem Projektverzeichnis und fügen Sie den folgenden Code hinzu:

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 ist eine vollständige Kommunikationsplattform und API-Lösung für WhatsApp. Entdecken Sie mehr als 100+ API-Anwendungsfälle und automatisieren Sie alles auf WhatsApp, indem Sie sich für eine kostenlose Testversion anmelden und in wenigen Minuten loslegen!

Mediennachrichten senden

In diesem Beispiel erstellen wir ein separates Programm namens send_media.js, um mehrere Bild-Mediennachrichten an verschiedene Telefonnummern zu senden, die aus einem Google-Sheets-Dokument geladen werden.

Der einfachste Weg, eine Mediennachricht zu senden, besteht darin, eine Download-URL für die Datei anzugeben. Wenn Ihre Datei noch nicht hochgeladen ist, können Sie sie in Google Drive hochladen und öffentlich zum Download freigeben, damit Wassenger sie später herunterladen und versenden kann.

Beispiel für eine Download-URL einer öffentlichen Datei in Google Drive:

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

Wichtig: Die angegebene Download-URL muss den Datei-Binärinhalt zurückgeben, andernfalls schlägt der Vorgang fehl.

Erstellen Sie eine neue Datei mit dem Namen send_media.js in Ihrem Projektverzeichnis und fügen Sie den folgenden Code hinzu:

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

Spielen Sie mit dem Code und führen Sie ihn in der Cloud aus, ohne Software auf Ihrem Computer installieren zu müssen. Erstellen Sie ein kostenloses Konto bei Replit und legen Sie in wenigen Minuten los

API-Token ersetzen

Stellen Sie in der Datei send_messages.js sicher, dass Sie das API-Token Ihres tatsächlichen Wassenger-Kontos definiert haben:

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

Optional: Falls Sie mehrere WhatsApp-Nummern in Ihrem Wassenger-Konto verbunden haben, können Sie angeben, welche WhatsApp-Nummer Sie für die Nachrichtenübermittlung verwenden möchten, indem Sie die eindeutige Wassenger-Geräte-ID (24-stellige hexadezimale Zeichenfolge) in der folgenden Zeile angeben:

// 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 ist eine vollständige Kommunikationsplattform und API-Lösung für WhatsApp. Entdecken Sie mehr als 100+ API-Anwendungsfälle und automatisieren Sie alles auf WhatsApp, indem Sie sich für eine kostenlose Testversion anmelden und in wenigen Minuten loslegen!

Programm ausführen

️➡️ Programm in der Cloud ausführen ⬅️

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

Programm auf Ihrem Computer ausführen

Bevor Sie das Programm ausführen: Wenn Sie planen, Hunderte von Nachrichten hintereinander zu senden, empfehlen wir, die Zustellgeschwindigkeit auf nicht mehr als 2–3 Nachrichten pro Minute zu begrenzen, um Sperrprobleme aufgrund von Anti-Spam-Richtlinien von WhatsApp zu vermeiden. Erfahren Sie hier mehr über Best Practices und wie Sie das Risiko reduzieren können.

Öffnen Sie ein Terminal in Ihrem Projektverzeichnis und führen Sie den folgenden Befehl aus, um das Skript send_messages.js auszuführen:

node send_messages.js

Ähnlich können Sie das Skript send_media.js ausführen, um Mediennachrichten zu senden:

node send_media.js

Wenn alles richtig eingerichtet ist, sollten Sie eine Ausgabe sehen, die anzeigt, dass die Nachrichten erfolgreich erstellt wurden:

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

Hinweis: Die Nachrichten werden in die Zustellwarteschlange Ihrer Nummer aufgenommen und asynchron im Hintergrund über die Zeit zugestellt, basierend auf der pro Minute zulässigen Zustellgeschwindigkeit Ihrer Nummer oder der manuell konfigurierten Zustellgeschwindigkeit, die Sie in den Einstellungen Ihrer Nummer definiert haben.

Nachrichten können je nach Anzahl der erstellten Nachrichten mehrere Minuten oder Stunden benötigen, bis sie effektiv an die Zieltelefonnummern über WhatsApp zugestellt werden. Sie können den Fortschritt der Nachrichtenlieferung im Web-Panel überwachen oder automatisch mithilfe von Webhook-Ereignissen.

Fazit

In diesem Tutorial haben Sie gelernt, wie Sie Nachrichten an Telefonnummern senden, die in einer CSV-Datei gespeichert sind, mithilfe von Node.js, der axios-Bibliothek und der Wassenger API.

Sie können die Datei numbers.csv aktualisieren und das Programm jederzeit ausführen, wenn Sie neue Nachrichten über Ihre mit Wassenger verbundene WhatsApp-Nummer senden möchten.

Sie können das Skript weiter anpassen, um zusätzliche Spalten zu verarbeiten, verschiedene Nachrichtentypen zu erstellen oder es nach Bedarf in Ihre Software zu integrieren.

🤩 🤖 Wassenger ist eine vollständige Kommunikationsplattform und API-Lösung für WhatsApp. Entdecken Sie mehr als 100+ API-Anwendungsfälle und automatisieren Sie alles auf WhatsApp, indem Sie sich für eine kostenlose Testversion anmelden und in wenigen Minuten loslegen!

Ready to transform your WhatsApp communication?

Start automating your customer interactions today with Wassenger

Get Started Free