whatsapp-web.js

repository·main·Indexed 12 days ago

https://github.com/wwebjs/whatsapp-web.js

A Node.js library for interacting with WhatsApp Web via a managed Puppeteer browser instance. It enables the creation of custom WhatsApp APIs with support for messaging, group management, media handling, and authentication strategies like LocalAuth and RemoteAuth. Version 1.34.7 requires Node.js v18.0.0 or higher.

Tokens
15.9K
Snippets
58
Records
77
Agent score
98%

What's inside whatsapp-web.js

  1. Supported WhatsApp features

    main

    whatsapp-web.js supports a wide range of features including:

    • Messaging: Send/receive text, media (images, audio, documents), stickers, contact cards, and locations. Note that sending video requires Google Chrome.
    • Group Management: Join by invite, get invite links, modify group info/settings, add/kick/promote/demote participants, and mention users/groups.
    • Interactions: Message replies, reacting to messages, creating and voting in polls, and setting user status.
    • Contacts: Get contact info and profile pictures, block/unblock contacts, and mute/unmute chats.
    • New Features: Support for Channels and Communities (Communities is currently in development).

    Note: Sending buttons and lists are currently marked as DEPRECATED.

  2. Quickstart: Create a basic WhatsApp bot

    main

    To get started, import the Client class from whatsapp-web.js. You will typically use a library like qrcode-terminal to display the QR code in your terminal for authentication. The lifecycle involves listening for the qr event to authenticate, the ready event to confirm connection, and the message event to handle incoming communications. Finally, call client.initialize() to start the process.

    const { Client } = require('whatsapp-web.js');
    const qrcode = require('qrcode-terminal');
    
    const client = new Client();
    
    client.on('qr', (qr) => {
        qrcode.generate(qr, { small: true });
    });
    
    client.on('ready', () => {
        console.log('Client is ready!');
    });
    
    client.on('message', (msg) => {
        if (msg.body == '!ping') {
            msg.reply('pong');
        }
    });
    
    client.initialize();
  3. Listen for Client Events

    main

    The Client class extends EventEmitter and emits several events during its lifecycle. Common events include:

    • ready: Emitted when the client has initialized and is ready to receive messages.
    • qr: Emitted when a QR code is received.
    • authenticated: Emitted when authentication is successful.
    • auth_failure: Emitted when there is an error restoring a session.
    • message: Emitted when a new message is received.
    • message_create: Emitted when a new message is created (including sent messages).
    • message_ack: Emitted when a message acknowledgment occurs.
    • disconnected: Emitted when the client is disconnected (reason can be a state or 'LOGOUT').
    • group_join: Emitted when a user joins a group.
    • group_leave: Emitted when a user leaves or is removed from a group.
    • contact_changed: Emitted when a contact changes their phone number.
  4. Manage WhatsApp Channels with the Channel class

    main

    The Channel class represents a WhatsApp Channel. It provides methods to manage channel metadata (name, description, profile picture), handle administrative tasks (inviting admins, transferring ownership, demoting admins), and interact with content (sending messages, fetching message history, and managing reactions).

    // Example of interacting with a Channel instance
    const channel = await client.getChannel(channelId);
    
    // Update channel info
    await channel.setSubject('New Channel Name');
    await channel.setDescription('New description here');
    
    // Send a message
    await channel.sendMessage('Hello Channel!');
    
    // Fetch message history
    const messages = await channel.fetchMessages({ limit: 50, fromMe: true });
  5. Initialize the Client

    main

    The Client class is the primary entry point for interacting with the WhatsApp Web API. To start using it, you must instantiate it with an options object and call the initialize() method. The initialize() method sets up the Puppeteer browser instance, handles authentication via your chosen authStrategy, and begins the injection process into WhatsApp Web.

    Key configuration options include:

    • authStrategy: Determines how sessions are saved and restored. If not provided, NoAuth is used.
    • puppeteer: An object containing Puppeteer launch options.
    • userAgent: A custom user agent string.
    • webVersion: The specific version of WhatsApp Web to use.
    • qrMaxRetries: Maximum number of times to refresh the QR code before disconnecting.
    • deviceName / browserName: Sets the device and browser names for the linked device.
    const { Client } = require('whatsapp-web.js');
    
    const client = new Client({
        // options
        authStrategy: new LocalAuth()
    });
    
    client.initialize();
  6. Configure Client Options

    main

    When instantiating the Client, you can pass a variety of configuration options to control the Puppeteer browser and the authentication lifecycle.

    OptionTypeDescription
    authStrategyAuthStrategyDetermines how to save and restore sessions.
    webVersionstringThe version of WhatsApp Web to use.
    webVersionCacheobjectConfiguration for retrieving the WhatsApp Web version.
    authTimeoutMsnumberTimeout for authentication selector in puppeteer.
    evalOnNewDocfunctionFunction to evaluate on every new document.
    puppeteerobjectPuppeteer launch options.
    qrMaxRetriesnumberHow many times the QR code should be refreshed before giving up.
    takeoverOnConflictbooleanIf another session is detected, take over the session in the current browser.
    takeoverTimeoutMsnumberTime to wait before taking over a session.
    userAgentstringUser agent to use in puppeteer.
    ffmpegPathstringPath to ffmpeg for video-to-webp conversion for stickers.
    bypassCSPbooleanSets bypassing of page's Content-Security-Policy.
    deviceNamestringSets the device name of a current linked device.
    browserNamestringSets the browser name of a current linked device.
    proxyAuthenticationobjectProxy Authentication object.
  7. Send an emoji reaction

    main

    Use sendReaction(messageId, reaction) to add an emoji reaction to a specific message. To remove a reaction, pass an empty string as the reaction argument.

    await client.sendReaction('MESSAGE_ID', '❤️');
    // To remove
    await client.sendReaction('MESSAGE_ID', '');
  8. Manage Profile Picture

    main

    Control your account's profile picture:

    • setProfilePicture(media): Sets your profile picture using a MessageMedia object. Returns true if successful.
    • deleteProfilePicture(): Deletes your current profile picture. Returns true if successful.
    // Set profile picture
    const media = new MessageMedia('image/jpeg', 'base64_string...', 'filename.jpg');
    await client.setProfilePicture(media);
    
    // Delete profile picture
    await client.deleteProfilePicture();
  9. Manage Customer Notes (WhatsApp Business)

    main

    For WhatsApp Business accounts, you can manage unstructured notes for customers:

    • addOrEditCustomerNote(userId, note): Adds or updates a note for a specific user.
    • getCustomerNote(userId): Retrieves the note for a user. Returns an object containing chatId, content, createdAt, id, modifiedAt, and type.
    // Add a note
    await client.addOrEditCustomerNote('USER_ID', 'This is a customer note');
    
    // Get a note
    const note = await client.getCustomerNote('USER_ID');
    console.log(note.content);
  10. Manage WhatsApp Labels

    main

    You can manage labels (primarily for WhatsApp Business) using the following methods:

    • getLabels(): Retrieves all current labels as an array of Label instances.
    • getLabelById(labelId): Retrieves a specific Label instance by its ID.
    • getChatLabels(chatId): Retrieves all labels assigned to a specific chat.
    • getChatsByLabelId(labelId): Retrieves all Chat instances associated with a specific label.
    • addOrRemoveLabels(labelIds, chatIds): Adds or removes specified labels from a list of chats. Note: This method only works on WhatsApp Business platforms (smba or smbi).
    // Get all labels
    const labels = await client.getLabels();
    
    // Get chats for a specific label
    const chats = await client.getChatsByLabelId('LABEL_ID');
    
    // Add/Remove labels for specific chats (Business only)
    await client.addOrRemoveLabels(['label_id_1'], ['chat_id_1', 'chat_id_2']);
  11. Access core data structures in whatsapp-web.js

    main

    The src/structures/index.js file serves as the central export aggregator for all primary data models and structures used within the library. When interacting with the Client or receiving events, you will work with these classes to represent various WhatsApp entities such as messages, chats, contacts, and media.

    Key categories of structures include:

    • Communication Entities: Chat, GroupChat, PrivateChat, Message, MessageMedia, Call, Reaction, Poll, PollVote.
    • Identity & Contact Entities: Contact, BusinessContact, PrivateContact, ClientInfo.
    • Commerce & Business Entities: Order, Product, Payment, Buttons, List, Label.
    • Social & Group Entities: GroupNotification, Channel, Broadcast, ScheduledEvent.
    • Spatial Entities: Location.
    // Example of how these structures are typically accessed via the library
    // (Note: Actual access pattern depends on the Client instance or event listeners)
    const { Message, Chat, Contact } = require('whatsapp-web.js/src/structures');