Baileys

repository·master·Indexed 27 days ago

https://github.com/whiskeysockets/baileys

A WebSockets-based TypeScript library for interacting with the WhatsApp Web API. Baileys allows developers to automate WhatsApp interactions without requiring a browser like Selenium or Chromium. It supports QR code and pairing code authentication, session persistence via useMultiFileAuthState, and sending various message types including text, media, polls, and reactions. The library also includes a Proto Extract tool for generating protobufs and utility functions for downloading media and managing chat metadata.

Tokens
9.5K
Snippets
31
Records
63
Agent score
95%

What's inside baileys

  1. Enable debug logging in Baileys

    master

    To inspect unhandled messages from WhatsApp and see raw communication in the console, enable the debug log level when initializing the socket using makeWASocket. This is useful for discovering new message types or protocol details.

    const sock = makeWASocket({
        logger: P({ level: 'debug' }),
    })
  2. Connect using a QR Code

    master

    To authenticate as a second WhatsApp client, you can scan a QR code. Use the printQRInTerminal: true option in your socket configuration to display the QR code in your terminal. You can also customize the browser identity using the Browsers constant (e.g., Browsers.ubuntu('My App')).

    import makeWASocket from '@whiskeysockets/baileys'
    
    const sock = makeWASocket({
        // can provide additional config here
        browser: Browsers.ubuntu('My App'),
        printQRInTerminal: true
    })
  3. Receive Full Message History

    master

    To sync and receive full message history, set syncFullHistory: true in your socket configuration. For better results (emulating a desktop connection), use a desktop browser configuration like Browsers.macOS('Desktop') or Browsers.ubuntu('Desktop').

    const sock = makeWASocket({
        ...otherOpts,
        // can use Windows, Ubuntu here too
        browser: Browsers.macOS('Desktop'),
        syncFullHistory: true
    })
  4. Save and Restore Authentication Sessions

    master

    To avoid re-scanning QR codes, you must persist your authentication state. The useMultiFileAuthState utility function is provided to save credentials to a local folder.

    Crucial: You must listen to the creds.update event and call the provided saveCreds function whenever it fires. Failure to save updated keys (authState.keys) will prevent messages from reaching recipients.

    import makeWASocket, { useMultiFileAuthState } from '@whiskeysockets/baileys'
    
    const { state, saveCreds } = await useMultiFileAuthState('auth_info_baileys')
    
    // will use the given state to connect
    // so if valid credentials are available -- it'll connect without QR
    const sock = makeWASocket({ auth: state })
    
    // this will be called as soon as the credentials are updated
    sock.ev.on('creds.update', saveCreds)
  5. Install Baileys

    master

    You can install the stable version of Baileys using yarn or npm. If you require the latest features and fixes and do not mind potential instability, you can install the edge version directly from GitHub.

    To use the library in your code, import the default export makeWASocket.

    # Install stable version
    yarn add @whiskeysockets/baileys
    
    # Install edge version
    yarn add github:WhiskeySockets/Baileys
    import makeWASocket from '@whiskeysockets/baileys'
  6. Implement a Data Store

    master

    Baileys does not include a built-in database for chats, contacts, or messages. While makeInMemoryStore is provided for simple in-memory usage, it is recommended to build a custom persistent data store for production environments to avoid high RAM usage.

    import makeWASocket, { makeInMemoryStore } from '@whiskeysockets/baileys'
    // the store maintains the data of the WA connection in memory
    // it can be written out to a file & read from it
    const store = makeInMemoryStore({ })
    // can be read from a file
    store.readFromFile('./baileys_store.json')
    // saves the state to a file every 10s
    setInterval(() => {
        store.writeToFile('./baileys_store.json')
    }, 10_000)
    
    const sock = makeWASocket({ })
    // will listen from this socket
    store.bind(sock.ev)
    
    sock.ev.on('chats.upsert', () => {
        // 'chats' => a KeyedDB instance
        console.log('got chats', store.chats.all())
    })
    
    sock.ev.on('contacts.upsert', () => {
        console.log('got contacts', Object.values(store.contacts))
    })
  7. Connect using a Pairing Code

    master

    If you want to connect without scanning a QR code, you can use a Pairing Code. Note that this method connects you as a single device (similar to WhatsApp Web).

    Requirements:

    1. Set printQRInTerminal: false in the socket config.
    2. Provide the phone number as a string containing only numbers (include the country code, but do not include +, (), or -).
    3. Call sock.requestPairingCode(number) to retrieve the code.
    import makeWASocket from '@whiskeysockets/baileys'
    
    const sock = makeWASocket({
        // can provide additional config here
        printQRInTerminal: false //need to be false
    })
    
    if (!sock.authState.creds.registered) {
        const number = 'XXXXXXXXXXX'
        const code = await sock.requestPairingCode(number)
        console.log(code)
    }
  8. Cache Group Metadata

    master

    When working with groups, it is highly recommended to implement a cache for group metadata to improve performance. You can provide an async function to the cachedGroupMetadata option in the socket config. You should update this cache by listening to groups.update and group-participants.update events.

    const groupCache = new NodeCache({stdTTL: 5 * 60, useClones: false})
    
    const sock = makeWASocket({
        cachedGroupMetadata: async (jid) => groupCache.get(jid)
    })
    
    sock.ev.on('groups.update', async ([event]) => {
        const metadata = await sock.groupMetadata(event.id)
        groupCache.set(event.id, metadata)
    })
    
    sock.ev.on('group-participants.update', async (event) => {
        const metadata = await sock.groupMetadata(event.id)
        groupCache.set(event.id, metadata)
    })
  9. Run the Baileys example script

    master

    To see a full implementation of common use cases, you can run the provided example.ts script. Follow these steps in your terminal:

    1. Navigate to the Baileys repository directory.
    2. Install dependencies using yarn.
    3. Execute the example script using yarn example.
    cd path/to/Baileys
    yarn
    yarn example