DEV Community

Cover image for How to Create a Whatsapp Bot With Node.js
Jagad Yudha Awali
Jagad Yudha Awali

Posted on • Edited on • Originally published at jagad.dev

How to Create a Whatsapp Bot With Node.js

Table of Contents

  1. Introduction
  2. Required Libraries
  3. How to Run Program
  4. Replying Messages
  5. Create Authentication
  6. Replying Messages With Image
  7. Implementation with the Yu-Gi-oh API
  8. Conclusion

Introduction

WhatsApp Messenger is a cross-platform messaging app that lets us send and receive messages in real time. WhatsApp Messenger is used by almost everyone on the planet. Unfortunately, unlike Telegram, Whatsapp's API usage is still restricted.

In this post, I'll show you how to make a free Whatsapp bot with the help of a third-party library.

Lets Go

Required Libraries

Installing the library from npm requires first installing node.js 12 or higher, followed by installing library from the npm package.

Installing whatsapp-web.js:

$ npm install whatsapp-web.js

or

$ yarn add whatsapp-web.js
Enter fullscreen mode Exit fullscreen mode

Installing qr-code-terminal:

$ npm install qr-code-terminal

or

$ yarn add qr-code-terminal
Enter fullscreen mode Exit fullscreen mode

How to Run Program

Create a file called app.js in the project and paste this code into it.

const qrcode = require("qrcode-terminal");
const { Client } = require("whatsapp-web.js");

const client = new Client();

client.initialize();

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

client.on("ready", () => {
  console.log("Client is ready!");
});
Enter fullscreen mode Exit fullscreen mode

Then, on the terminal or command prompt, type this command.

$ node app

or

$ node app.js
Enter fullscreen mode Exit fullscreen mode

When the command is executed, a QR code appears, which we will scan with the Whatsapp account we used to create the bot.

QR code

Replying Messages

The goal of creating a bot is for it to be able to respond to messages. So, in the project that we created before, paste the following code.

//Replying Messages
client.on("message", (message) => {
  if (message.body === "hello") {
    message.reply("Hiiiii");
  }
});
Enter fullscreen mode Exit fullscreen mode

When someone else types a hello message to bot, we'll make the bot reply to it.

Replying message

Create Authentication

The function of creating authentication is that we don't have to login (scan QR code) every time we run an app.js.

Here is the code to create authentication :

const qrcode = require("qrcode-terminal");
const { Client, LocalAuth } = require("whatsapp-web.js");

//store authentication data to a file
const client = new Client({
  authStrategy: new LocalAuth(),
});

client.initialize();

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

client.on("authenticated", () => {
  console.log("AUTHENTICATED");
});

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

client.on("message", (message) => {
  if (message.body === "hello") {
    message.reply("Hiiiii");
  }
});
Enter fullscreen mode Exit fullscreen mode

Replying Messages With Image From Url

On the other hand, bots are less interactive if they only reply with text messages, so we can reply to messages using media such as images.

Here is the code to make bot replying with media:

const qrcode = require("qrcode-terminal");
const { Client, LocalAuth, MessageMedia } = require("whatsapp-web.js");

const client = new Client({
  authStrategy: new LocalAuth(),
});

client.initialize();

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

client.on("authenticated", () => {
  console.log("AUTHENTICATED");
});

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

//Replying Messages with image from url
client.on("message", async (message) => {
  if (message.body === "meme") {
    //get media from url
    const media = await MessageMedia.fromUrl(
      "https://user-images.githubusercontent.com/41937681/162612030-11575069-33c2-4df2-ab1b-3fb3cb06f4cf.png"
    );

    //replying with media
    client.sendMessage(message.from, media, {
      caption: "meme",
    });
  }
});
Enter fullscreen mode Exit fullscreen mode

We'll make the bot respond with an image whenever someone else types a meme message.

Replying Message with Media

Implementation with the Yu-Gi-oh API

to prove that the library can be adjusted to fit the needs of the case study. In this case, I'll use the YGOPRODeck Yu-Gi-Oh! API.

The following is how the Yu-Gi-Oh! bot that we will make works:

  1. Someone typed Yugioh Card Name via WhatsApp message.
  2. The card's name will be checked against the database.
  3. If the Yugioh Card is found in the database, the bot will respond with the card's image.

An extra library called Axios is required for the WhatsApp bot to be able to send requests to the Yu-Gi-Oh! API:

$ npm install axios

or

$ yarn add axios
Enter fullscreen mode Exit fullscreen mode

Here is the complete code of the Yu-Gi-Oh! bot:

const { Client, LocalAuth, MessageMedia } = require("whatsapp-web.js");
const axios = require("axios");

const client = new Client({
  authStrategy: new LocalAuth(),
});

client.initialize();

client.on("qr", (qr) => {
  console.log("QR RECEIVED", qr);
});

client.on("authenticated", () => {
  console.log("AUTHENTICATED");
});

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

client.on("message", async (msg) => {
  if (msg.body) {
    axios
      .get(
        `https://db.ygoprodeck.com/api/v7/cardinfo.php?name=${encodeURIComponent(
          msg.body
        )}`
      )
      .then(async (res) => {
        if (res.data.error) {
          msg.reply("No card matching your query was found in the database.");
        } else {
          const media = await MessageMedia.fromUrl(
            res.data.data[0].card_images[0].image_url
          );
          client.sendMessage(msg.from, media, {
            caption: `Name : ${res.data.data[0].name}\nType : ${res.data.data[0].type}\nDesc : ${res.data.data[0].desc}
            `,
          });
        }
      })
      .catch((error) => {
        console.error(error);
      });
  }
});
Enter fullscreen mode Exit fullscreen mode

I'm attempting to type a message using the text from the Yu-Gi-Oh! card named Card Shuffle and then the bot responds with a photo and description of the card we sent before.

Yu-Gi-Oh API

I was trying to type a message using another card name, called Burning Bamboo Sword.

Yu-Gi-Oh API

Conclusion

Because the WhatsApp API is still limited, third-party tools like whatsapp-web.js help a lot. However, since this library is not affiliated with WhatsApp, there are still many problems.

The code of this project lives at : https://github.com/jagadyudha/yugioh-whatsapp-bot

This article was originally published on How to Create a Whatsapp Bot With Node.js — Jagad Yudha Awali

Top comments (2)

Collapse
 
danedoubell profile image
Dane Doubell

A very nice implementation to get people started with whatsapp-web.js

Collapse
 
purpshell profile image
Rajeh Taher

Agreed