### Basic Client Initialization and Event Handling Source: https://github.com/wwebjs/whatsapp-web.js/blob/main/README.md Initialize the client, generate a QR code for authentication, and handle 'ready' and 'message' events. This is a fundamental example for starting with the library. ```javascript 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(); ``` -------------------------------- ### Install whatsapp-web.js Source: https://github.com/wwebjs/whatsapp-web.js/blob/main/docs/index.html Install the library using npm, yarn, or pnpm. Node.js v18.0.0 or higher is required. ```bash npm install whatsapp-web.js ``` ```bash yarn add whatsapp-web.js ``` ```bash pnpm add whatsapp-web.js ``` -------------------------------- ### Install whatsapp-web.js Source: https://github.com/wwebjs/whatsapp-web.js/blob/main/README.md Install the library using npm, yarn, or pnpm. Node.js v18.0.0 or higher is required. ```sh npm install whatsapp-web.js yarn add whatsapp-web.js pnpm add whatsapp-web.js ``` -------------------------------- ### initialize Source: https://github.com/wwebjs/whatsapp-web.js/blob/main/docs/Client.html Initializes the client, setting up event listeners and starting the authentication process. ```APIDOC ## initialize() ### Description Sets up events and requirements, kicks off authentication request ### Method async ``` -------------------------------- ### Client#getLabels() Source: https://github.com/wwebjs/whatsapp-web.js/blob/main/docs/index.html Gets all labels. ```APIDOC ## Client#getLabels() ### Description Gets all labels. ### Method `getLabels` ### Returns `Promise>` - A promise that resolves to an array of label objects. ``` -------------------------------- ### Client#getState() Source: https://github.com/wwebjs/whatsapp-web.js/blob/main/docs/index.html Gets the current state of the client. ```APIDOC ## Client#getState() ### Description Gets the current state of the client. ### Method `getState` ### Returns `Promise` - A promise that resolves to the current state (e.g., 'CONNECTED', 'DISCONNECTED', 'PAIRING'). ``` -------------------------------- ### ready Source: https://github.com/wwebjs/whatsapp-web.js/blob/main/docs/Client.html Emitted when the client has finished its initialization process and is ready to start receiving and sending messages. ```APIDOC ## Event: ready ### Description Emitted when the client has initialized and is ready to receive messages. ``` -------------------------------- ### Get Contact Country Code Source: https://github.com/wwebjs/whatsapp-web.js/blob/main/docs/structures_Contact.js.html Extracts and returns the country code from the contact's ID. For example, '1541859685@c.us' would return '1'. ```javascript async getCountryCode() { return await this.client.getCountryCode(this.id._serialized); } ``` -------------------------------- ### createCallLink Source: https://github.com/wwebjs/whatsapp-web.js/blob/main/docs/Client.js.html Generates a WhatsApp call link for either a video or voice call, specifying the desired start time. ```APIDOC ## createCallLink ### Description Generates a WhatsApp call link for either a video or voice call, specifying the desired start time. ### Method ```javascript async createCallLink(startTime, callType) ``` ### Parameters #### Arguments * **startTime** (Date) - Required - The start time of the call. * **callType** (string) - Required - The type of WhatsApp call link to generate. Valid values are: `video` | `voice`. ### Returns * **Promise<string>** - The WhatsApp call link (e.g., `https://call.whatsapp.com/video/XxXxXxXxXxXxXx`) or an empty string if generation failed. ### Throws * **Error** - If an invalid `callType` is provided. ``` -------------------------------- ### Client#initialize() Source: https://github.com/wwebjs/whatsapp-web.js/blob/main/docs/index.html Initializes the client and connects to WhatsApp. ```APIDOC ## Client#initialize() ### Description Initializes the client and connects to WhatsApp. ### Method `initialize` ### Returns `Promise` - A promise that resolves when the client has successfully initialized. ``` -------------------------------- ### Get Message by ID Source: https://github.com/wwebjs/whatsapp-web.js/blob/main/docs/structures_Message.js.html Retrieves a message by its ID. It first tries to get the message directly, and if not found, it attempts to fetch it from a list of messages. ```javascript window.require('WAWebCollections').Msg.get(msgId) || (await window.require('WAWebCollections').Msg.getMessagesById([msgId]))?.messages?.[0]; ``` -------------------------------- ### Get Labels for a Chat - whatsapp-web.js Source: https://github.com/wwebjs/whatsapp-web.js/blob/main/docs/util_Injected_Utils.js.html Retrieves all labels associated with a specific chat. It first gets the chat object and then maps its label IDs to label objects. ```javascript window.WWebJS.getChatLabels = async (chatId) => { const chat = await window.WWebJS.getChat(chatId); return (chat.labels || []).map((id) => window.WWebJS.getLabel(id)); }; ``` -------------------------------- ### Basic Client Initialization and Event Handling Source: https://github.com/wwebjs/whatsapp-web.js/blob/main/docs/index.html Initialize the client, handle QR code generation, and respond to messages. The client requires initialization to connect to WhatsApp Web. ```javascript 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(); ``` -------------------------------- ### MessageMedia Constructor Source: https://github.com/wwebjs/whatsapp-web.js/blob/main/docs/MessageMedia.html Initializes a new MessageMedia instance with media details. ```APIDOC ## new MessageMedia(mimetype, data, filename, filesize) ### Description Initializes a new MessageMedia instance with the provided media details. ### Parameters - **mimetype** (string) - Required - MIME type of the attachment. - **data** (string) - Required - Base64-encoded data of the file. - **filename** (nullable string) - Optional - Document file name. Can be null. - **filesize** (nullable number) - Optional - Document file size in bytes. Can be null. ``` -------------------------------- ### getCustomerNote Source: https://github.com/wwebjs/whatsapp-web.js/blob/main/docs/GroupChat.html Get a customer note. ```APIDOC ## getCustomerNote() ### Description Get a customer note. ### Inherited from [Chat#getCustomerNote](Chat.html#getCustomerNote) ### See also [https://faq.whatsapp.com/1433099287594476](https://faq.whatsapp.com/1433099287594476) ``` -------------------------------- ### Initialize Browser and Page Source: https://github.com/wwebjs/whatsapp-web.js/blob/main/docs/Client.js.html Sets up the Puppeteer browser and page instances, configures proxy authentication, user agent, and bypasses CSP if enabled. It then navigates to the WhatsApp URL and injects necessary scripts. ```javascript if (this.options.proxyAuthentication !== undefined) { await page.authenticate(this.options.proxyAuthentication); } if (this.options.userAgent !== false) { await page.setUserAgent(this.options.userAgent); } if (this.options.bypassCSP) await page.setBypassCSP(true); this.pupBrowser = browser; this.pupPage = page; await this.authStrategy.afterBrowserInitialized(); await this.initWebVersionCache(); if (this.options.evalOnNewDoc !== undefined) { await page.evaluateOnNewDocument(this.options.evalOnNewDoc); } await page.goto(WhatsWebURL, { waitUntil: 'load', timeout: 0, referer: 'https://whatsapp.com/', }); await this.inject(); ``` -------------------------------- ### Client#getContacts() Source: https://github.com/wwebjs/whatsapp-web.js/blob/main/docs/index.html Gets all contacts the client has. ```APIDOC ## Client#getContacts() ### Description Gets all contacts the client has. ### Method `getContacts` ### Returns `Promise>` - A promise that resolves to an array of contact objects. ``` -------------------------------- ### Initialize Settings Module Source: https://github.com/wwebjs/whatsapp-web.js/blob/main/docs/util_Injected_Store.js.html Initializes the Settings module by merging general user preferences and notification settings, and setting the push name. ```javascript window.Store.Settings = { ...window.require('WAWebUserPrefsGeneral'), ...window.require('WAWebUserPrefsNotifications'), setPushname: window.require('WAWebSetPushnameConnAction').setPushname }; ``` -------------------------------- ### Initialize LocalWebCache Source: https://github.com/wwebjs/whatsapp-web.js/blob/main/docs/webCache_LocalWebCache.js.html Instantiate LocalWebCache with custom path and strict mode options. The default cache path is './.wwebjs_cache/'. ```javascript const { LocalWebCache } = require('./webCache/LocalWebCache'); const cache = new LocalWebCache({ path: './my_cache/', strict: true }); ``` -------------------------------- ### Client#getChats() Source: https://github.com/wwebjs/whatsapp-web.js/blob/main/docs/index.html Gets all chats the client has. ```APIDOC ## Client#getChats() ### Description Gets all chats the client has. ### Method `getChats` ### Returns `Promise>` - A promise that resolves to an array of chat objects. ``` -------------------------------- ### Initialize Sticker Tools Module Source: https://github.com/wwebjs/whatsapp-web.js/blob/main/docs/util_Injected_Store.js.html Initializes the StickerTools module with image utilities and WebP metadata handling for sticker creation. ```javascript window.Store.StickerTools = { ...window.require('WAWebImageUtils'), ...window.require('WAWebAddWebpMetadata') }; ``` -------------------------------- ### Client#getBroadcasts() Source: https://github.com/wwebjs/whatsapp-web.js/blob/main/docs/index.html Gets all broadcast lists. ```APIDOC ## Client#getBroadcasts() ### Description Gets all broadcast lists. ### Method `getBroadcasts` ### Returns `Promise>` - A promise that resolves to an array of broadcast lists. ``` -------------------------------- ### getState Source: https://github.com/wwebjs/whatsapp-web.js/blob/main/docs/Client.js.html Gets the current connection state for the client. ```APIDOC ## getState ### Description Gets the current connection state for the client. ### Method GET ### Endpoint /client/state ### Parameters None ### Response #### Success Response (200) - **state** (WAState) - The current state of the WebSocket connection. ### Response Example ```json { "state": "CONNECTED" } ``` ``` -------------------------------- ### Client Initialization Source: https://github.com/wwebjs/whatsapp-web.js/blob/main/docs/Client.js.html Initializes a new Client instance. The constructor accepts an options object to configure various aspects of the client, such as authentication strategy, web version, and Puppeteer settings. ```APIDOC ## Client Constructor ### Description Initializes a new Client instance. The constructor accepts an options object to configure various aspects of the client, such as authentication strategy, web version, and Puppeteer settings. ### Parameters #### Options Object - **authStrategy** (AuthStrategy) - Determines how to save and restore sessions. If not set, NoAuth will be used. - **webVersion** (string) - The version of WhatsApp Web to use. Use options.webVersionCache to configure how the version is retrieved. - **webVersionCache** (object) - Determines how to retrieve the WhatsApp Web version. Defaults to a local cache (LocalWebCache) that falls back to latest if the requested version is not found. - **authTimeoutMs** (number) - Timeout for authentication selector in puppeteer - **evalOnNewDoc** (function) - function to eval on new doc - **puppeteer** (object) - Puppeteer launch options. View docs here: https://github.com/puppeteer/puppeteer/ - **qrMaxRetries** (number) - How many times should the qrcode be refreshed before giving up - **takeoverOnConflict** (number) - If another whatsapp web session is detected (another browser), take over the session in the current browser - **takeoverTimeoutMs** (number) - How much time to wait before taking over the session - **userAgent** (string) - User agent to use in puppeteer - **ffmpegPath** (string) - Ffmpeg path to use when formatting videos to webp while sending stickers - **bypassCSP** (boolean) - Sets bypassing of page's Content-Security-Policy. - **deviceName** (string) - Sets the device name of a current linked device., i.e.: 'TEST'. - **browserName** (string) - Sets the browser name of a current linked device, i.e.: 'Firefox'. - **proxyAuthentication** (object) - Proxy Authentication object. ### Events - Client#qr - Client#authenticated - Client#auth_failure - Client#ready - Client#message - Client#message_ack - Client#message_create - Client#message_revoke_me - Client#message_revoke_everyone - Client#message_ciphertext - Client#message_edit - Client#media_uploaded - Client#group_join - Client#group_leave - Client#group_update - Client#disconnected - Client#change_state - Client#contact_changed - Client#group_admin_changed - Client#group_membership_request - Client#vote_update ``` -------------------------------- ### Client#event:ready Source: https://github.com/wwebjs/whatsapp-web.js/blob/main/docs/index.html Emitted when the client is ready and has successfully connected to WhatsApp. ```APIDOC ## Client#event:ready ### Description Emitted when the client is ready and has successfully connected to WhatsApp. ### Event `ready` ``` -------------------------------- ### Client#getMessageById(messageId) Source: https://github.com/wwebjs/whatsapp-web.js/blob/main/docs/index.html Gets a message by its ID. ```APIDOC ## Client#getMessageById(messageId) ### Description Gets a message by its ID. ### Method `getMessageById` ### Parameters #### Path Parameters - **messageId** (string) - Required - The ID of the message. ### Returns `Promise` - A promise that resolves to the message object. ``` -------------------------------- ### Configure Chat and Backend Utilities Source: https://github.com/wwebjs/whatsapp-web.js/blob/main/docs/util_Injected.js.html Sets up chat finding logic, backend detection, and feature flags for the WhatsApp Web environment. ```javascript if (!window.Store.Chat._find) { window.Store.Chat._find = e => { const target = window.Store.Chat.get(e); return target ? Promise.resolve(target) : Promise.resolve({ id: e }); }; } // eslint-disable-next-line no-undef if ((m = window.mR.findModule('ChatCollection')[0]) && m.ChatCollection && typeof m.ChatCollection.findImpl === 'undefined' && typeof m.ChatCollection._find !== 'undefined') m.ChatCollection.findImpl = m.ChatCollection._find; // TODO remove these once everybody has been updated to WWebJS with legacy sessions removed const _linkPreview = window.mR.findModule('queryLinkPreview'); if (_linkPreview && _linkPreview[0] && _linkPreview[0].default) { window.Store.Wap = _linkPreview[0].default; } const _isMDBackend = window.mR.findModule('isMDBackend'); if(_isMDBackend && _isMDBackend[0] && _isMDBackend[0].isMDBackend) { window.Store.MDBackend = _isMDBackend[0].isMDBackend(); } else { window.Store.MDBackend = true; } const _features = window.mR.findModule('FEATURE_CHANGE_EVENT')[0]; if(_features) { window.Store.Features = _features.LegacyPhoneFeatures; } ``` -------------------------------- ### Client#getLabelById(labelId) Source: https://github.com/wwebjs/whatsapp-web.js/blob/main/docs/index.html Gets a label by its ID. ```APIDOC ## Client#getLabelById(labelId) ### Description Gets a label by its ID. ### Method `getLabelById` ### Parameters #### Path Parameters - **labelId** (string) - Required - The ID of the label. ### Returns `Promise