Tous les articles
Tutorials10 juin 20261 minute de lecture

Introduction to Baileys: Developing intelligent bots on WhatsApp

Introduction to Baileys: Developing intelligent bots on WhatsApp

The Baileys library is currently one of the most agile and powerful open-source solutions for communicating directly with the WhatsApp Web API without incurring expensive commercial messaging fees.

Why use Baileys?

Unlike its competitors that emulate a complete browser through Puppeteer (which consumes a gigantic amount of server RAM), Baileys interacts directly through encrypted WebSocket streams.

Its key advantages include:

  • Minimal resource consumption: Ideal for running on small containers or affordable VPS servers.
  • Fast execution: Near-instant sending and receiving of messages in real time.
  • Rich API: Complete management of text messages, images, audio files, documents, and quick interaction buttons.

Quick Start Guide with TypeScript

Here is how to set up an instant connection point:

import makeWASocket, { useMultiFileAuthState } from '@whiskeysockets/baileys';

async function connectToWhatsApp() {
  // Handles session persistence for automatic reconnection
  const { state, saveCreds } = await useMultiFileAuthState('session_whatsapp_auth');
  
  const sock = makeWASocket({
    auth: state,
    printQRInTerminal: true // Displays the QR Code to link the device
  });

  sock.ev.on('creds.update', saveCreds);

  sock.ev.on('messages.upsert', async m => {
    const msg = m.messages[0];
    if (!msg.key.fromMe && msg.message) {
      console.log('New message received:', msg.message.conversation);
      
      // Interactive ping-pong example
      if (msg.message.conversation?.toLowerCase() === 'ping') {
        await sock.sendMessage(msg.key.remoteJid!, { text: 'Pong! πŸ“' });
      }
    }
  });
}

This simple script sets up an event handler that listens for incoming messages.

La publicitΓ© permet de garder ce blog gratuit.

Discussion (0)

Join the discussion!

To post a comment or share your thoughts on this article, sign in securely in one click with your Google account.

Loading discussion...