Skip to main content

Command Palette

Search for a command to run...

Write your first WhatsApp bot with baileys.js and baileys-bottle

Wanna write your own WhatsApp bot without getting WhatsApp API TOKEN? if yes I got you covered :)

Published
4 min read
Write your first WhatsApp bot with baileys.js and baileys-bottle

I have been creating WhatsApp bots for fun, and in this blog post, I'd like to 'enlighten' you on how you can set up your bots quickly and without getting stuck as I did at the beginning.

Warn: Not Suitable for production-ready bot development

Requirements

  • Nodejs(only basic)

with these steps

  • intro
  • installation
  • get your hands dirty with code
  • OwO

Intro

  • Baileys.js

Baileys supports interacting with the multi-device & web versions of WhatsApp.

Baileys does not require Selenium or any other browser to interface with WhatsApp Web, it does so directly using a WebSocket. Not running Selenium or Chromium saves you like half a gig of ram :/

  • Baileys bottle

A little package made by deadlinecode for storing all the data from baileys in whatever database you want to use by using typeorm

TypeORM currently supports:

  • MySQL
  • MariaDB
  • Postgres
  • CockroachDB
  • SQLite
  • Microsoft SQL Server
  • Oracle
  • SAP Hana
  • sql.js

ps: we gonna use SQLite for keeping this simple :)

Installation

  1. First set up your nodejs project if you haven't yet with ( Run these commands in your terminal/cmd)
    npm init -y
    
  2. Install required packages
    npm i @adiwajshing/baileys
    
    npm i baileys-bottle
    
    npm i qrcode-terminal
    
  3. create file app.js

Coding and stuff

  • gotta do some importing

    import makeWASocket, {
    DisconnectReason,
    fetchLatestBaileysVersion,
    } from "@adiwajshing/baileys";
    import log from "@adiwajshing/baileys/lib/Utils/logger";
    import BaileysBottle from "..";
    import { Boom } from "@hapi/boom";
    
  • setting up datastore

  const logger = log.child({});
  logger.level = "silent";

  const { auth, store } = await BaileysBottle({
    type: "sqlite",
    database: "db.sqlite",
  });

  const { state, saveState } = await auth.useAuthHandle();
  • and finally
 const startSocket = async () => {
    const { version, isLatest } = await fetchLatestBaileysVersion();
    console.log(`using WA v${version.join(".")}, isLatest: ${isLatest}`);

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

    store.bind(sock.ev);

    sock.ev.process(
     async (events) => {

      //
      // Start your bot code here...
      //
      if(events['messages.upsert']) {
                const upsert = events['messages.upsert'];
                console.log('recv messages ', JSON.stringify(upsert, undefined, 2));
                if(upsert.type === 'notify') {
                    for(const msg of upsert.messages) {
                        if(!msg.key.fromMe) {
              // mark message as read
                            await sock!.readMessages([msg.key]);
                        }
                    }
                }
            }
      //
      // End your bot code here...
      //

      // credentials updated -- save them
            if(events['creds.update']) saveState();


      if(events['connection.update']) {
        const update = events['connection.update'];
                const { connection, lastDisconnect } = update;
        connection === "open"
        ? console.log("Connected")
        : connection === "close"
        ? (lastDisconnect?.error as Boom)?.output?.statusCode !==
          DisconnectReason.loggedOut
          ? startSocket()
          : console.log("Connection closed. You are logged out.")
        : null;
      }
    });
  };

  startSocket();

now run your project ('node app.js'), and you will get QRcode in your terminal now scan it with your WhatsApp and the bot will come to life

now above code only mark the message as read.

you can use these methods for sending replies, as text, media message,s or link preview

OwO

  • bonus

use this for creating custom Whatsapp stickers with ur bot

  • complete code
import makeWASocket, {
  DisconnectReason,
  fetchLatestBaileysVersion,
} from "@adiwajshing/baileys";
import log from "@adiwajshing/baileys/lib/Utils/logger";
import BaileysBottle from "..";
import { Boom } from "@hapi/boom";

const main = async () => {
  const logger = log.child({});
  logger.level = "silent";

  const { auth, store } = await BaileysBottle({
    type: "sqlite",
    database: "db.sqlite",
  });

  const { state, saveState } = await auth.useAuthHandle();

  const startSocket = async () => {
    const { version, isLatest } = await fetchLatestBaileysVersion();
    console.log(`using WA v${version.join(".")}, isLatest: ${isLatest}`);

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

    store.bind(sock.ev);

    sock.ev.process(
     async (events) => {

      //
      // Start your bot code here...
      //
      if(events['messages.upsert']) {
                const upsert = events['messages.upsert'];
                console.log('recv messages ', JSON.stringify(upsert, undefined, 2));
                if(upsert.type === 'notify') {
                    for(const msg of upsert.messages) {
                        if(!msg.key.fromMe) {
              // mark message as read
                            await sock!.readMessages([msg.key]);
                        }
                    }
                }
            }
      //
      // End your bot code here...
      //

      // credentials updated -- save them
            if(events['creds.update']) saveState();


      if(events['connection.update']) {
        const update = events['connection.update'];
                const { connection, lastDisconnect } = update;
        connection === "open"
        ? console.log("Connected")
        : connection === "close"
        ? (lastDisconnect?.error as Boom)?.output?.statusCode !==
          DisconnectReason.loggedOut
          ? startSocket()
          : console.log("Connection closed. You are logged out.")
        : null;
      }
    });
  };

  startSocket();
};

main();

Have a nice day, Take care :)