Creating a WhatsApp Bot with Node.js: A Step-by-Step Guide

ยท

5 min read

Introduction:

WhatsApp is one of the most popular messaging platforms in the world, with over 2 billion monthly active users. With the rise of chatbots, businesses and developers are looking for ways to leverage WhatsApp to provide customer support, promote products, and engage with users. In this blog post, we'll show you how to create a WhatsApp bot using Node.js and the @whiskeysockets/baileys library.

Prerequisites:

  • Node.js installed on your machine

  • A WhatsApp account

  • Basic knowledge of JavaScript and Node.js

Step 1: Setting up the Project

To start, create a new Node.js project and install the required dependencies:

npm init
npm install @whiskeysockets/baileys express

Step 2: Creating the WhatsApp Bot

Create a new file called index.js and add the following code:

const express = require('express');
const { default: makeWASocket, DisconnectReason, useMultiFileAuthState } = require('@whiskeysockets/baileys');

const app = express();
app.use(express.json());

let sock = null;

// Welcome message
const WELCOME_MESSAGE = `Welcome to our WhatsApp bot! ๐Ÿš€

You can interact with me in the following ways:
1. Type 'joke' to hear a joke.
2. Type 'quote' to get a quote.
3. Type 'funfact' to learn a fun fact.
4. Type 'help' to see this message again.

What would you like to do?`;

// Enhanced message handler
async function handleIncomingMessage(m) {
  try {
    // Handle greetings
    if (m.message.conversation.includes('hi') || m.message.conversation.includes('hello')) {
      await sock.sendMessage(m.key.remoteJid, { text: WELCOME_MESSAGE });
      return;
    }

    // Handle joke
    if (m.message.conversation.includes('joke')) {
      await sock.sendMessage(m.key.remoteJid, { text: 'Why don\'t scientists trust atoms? Because they make up everything!' });
      return;
    }

    // Handle quote
    if (m.message.conversation.includes('quote')) {
      await sock.sendMessage(m.key.remoteJid, { text: 'Believe you can and you\'re halfway there. - Theodore Roosevelt' });
      return;
    }

    // Handle fun fact
    if (m.message.conversation.includes('funfact')) {
      await sock.sendMessage(m.key.remoteJid, { text: 'Butterflies taste with their feet!' });
      return;
    }

    // Handle help
    if (m.message.conversation.includes('help')) {
      await sock.sendMessage(m.key.remoteJid, { text: WELCOME_MESSAGE });
      return;
    }

    // Default response for unrecognized messages
    await sock.sendMessage(m.key.remoteJid, { text: WELCOME_MESSAGE });
  } catch (error) {
    console.error('Error in handleIncomingMessage:', error);
  }
}

// Initialize WhatsApp connection
async function connectToWhatsApp() {
  try {
    console.log('Attempting to connect to WhatsApp...');

    const authDir = './auth_info_baileys';
    if (!fs.existsSync(authDir)) {
      console.log('Creating auth directory...');
      fs.mkdirSync(authDir);
    }

    const { state, saveCreds } = await useMultiFileAuthState('auth_info_baileys');
    console.log('Auth state loaded');

    sock = makeWASocket({
      printQRInTerminal: true,
      auth: state
    });

    sock.ev.on('connection.update', (update) => {
      const { connection, lastDisconnect } = update;

      if (connection === 'close') {
        const shouldReconnect = lastDisconnect?.error?.output?.statusCode !== DisconnectReason.loggedOut;
        if (shouldReconnect) {
          connectToWhatsApp();
        }
      } else if (connection === 'open') {
        console.log('Connected to WhatsApp!');
      }
    });

    sock.ev.on('messages.upsert', async ({ messages }) => {
      const m = messages[0];
      if (m.key.fromMe) return;
      await handleIncomingMessage(m);
    });

    sock.ev.on('creds.update', saveCreds);
  } catch (error) {
    console.error('Error in connectToWhatsApp:', error);
  }
}

// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

// Initialize WhatsApp connection
connectToWhatsApp().catch(err => {
  console.error('Fatal error in main:', err);
});

Step 3: Scanning the QR Code

To connect to WhatsApp, you need to scan the QR code generated by the @whiskeysockets/baileys library. To do this, follow these steps:

  1. Open the terminal and run the command node index.js to start the server.

  2. Open WhatsApp on your phone and go to the settings menu.

  3. Tap on "Linked Devices" and then tap on "Link a Device".

  4. Scan the QR code generated by the @whiskeysockets/baileys library.

  5. Once the QR code is scanned, you will be connected to WhatsApp and can start receiving and sending messages.

Step 4: Testing the Bot

To test the bot, send a message to the WhatsApp number associated with the bot. The bot will respond with a welcome message and provide options for the user to choose from.

Step 5: Handling Errors

To handle errors, you can add error handling to your code to detect when the authentication credentials are no longer valid, and then prompt the user to re-authenticate with WhatsApp.

Conclusion:

In this blog post, we showed you how to create a WhatsApp bot using Node.js and the @whiskeysockets/baileys library. We covered the steps to set up the project, create the WhatsApp bot, scan the QR code, test the bot, and handle errors. With this knowledge, you can create your own WhatsApp bot to provide customer support, promote products, and engage with users.

Example Use Cases:

  • Customer support: You can use the WhatsApp bot to provide customer support for your business. The bot can answer frequently asked questions, provide order tracking information, and help customers with returns or exchanges.

  • Marketing: You can use the WhatsApp bot to promote your business or product. The bot can send special offers or discounts to users, provide information about new products or services, and help users find what they're looking for.

  • Education: You can use the WhatsApp bot to provide educational content or resources. The bot can send study tips or reminders, provide access to online courses or tutorials, and help students with homework or research projects.

Best Practices:

  • Test your bot thoroughly before deploying it to production.

  • Use a robust and reliable messaging platform to ensure that messages are delivered correctly.

  • Provide clear and concise instructions to users on how to interact with your bot.

  • Use analytics and reporting to track user interactions with your bot and identify areas for improvement.

  • Continuously monitor and update your bot to ensure that it remains secure and effective.

By following these steps and best practices, you can create a WhatsApp bot that provides value to your users and helps you achieve your business goals.

Happy Coding!

ย