wa-multi-session

repository·master·Indexed 42 days ago

https://github.com/mimamch/wa-multi-session

A lightweight WhatsApp multi-session library built on top of Baileys, version 4.3.1. It enables developers to manage multiple WhatsApp connections within a single application without a browser or Selenium. The library supports session persistence via RedisAdapter and SQLiteAdapter, and provides comprehensive methods for sending text, images, videos, documents, audio, and polls, as well as handling incoming messages and profile information.

Tokens
9.4K
Snippets
41
Records
43
Agent score
53%

What's inside wa-multi-session

  1. Handle incoming messages and save media

    master

    Use the onMessageReceived callback in the Whatsapp constructor to react to incoming messages.

    Inside the callback, you can:

    • Check if a message is from yourself or a status update using msg.key.fromMe or msg.key.remoteJid.
    • Read the message using whatsapp.readMessage.
    • Trigger a typing indicator.
    • Reply to a message using the answering option in sendText to quote the original message.
    • Save media files (images, videos, documents) directly from the message object using msg.saveImage(path), msg.saveVideo(path), or msg.saveDocument(path) (note: saveDocument path should not include the extension).
    const whatsapp = new Whatsapp({
      adapter: new RedisAdapter({
        url: "redis://localhost:6379",
      }),
      onMessageReceived: async (msg) => {
        if (msg.key.fromMe || msg.key.remoteJid?.includes("status")) return;
        
        const sender = msg.key.participant || msg.key.remoteJid!;
        
        // Read message
        await whatsapp.readMessage({
          sessionId: msg.sessionId,
          key: msg.key,
        });
    
        // Save media if available
        if (msg.message?.imageMessage) {
          msg.saveImage("./myimage.jpg");
        }
    
        // Reply to user
        await whatsapp.sendText({
          sessionId: msg.sessionId,
          to: sender,
          text: `You said: ${msg.message?.conversation || ""}`,
          answering: msg,
        });
      },
    });
  2. Initialize the Whatsapp instance with an adapter

    master

    To use the library, you must create a new Whatsapp instance and provide an adapter for session persistence. The RedisAdapter is the default recommended adapter, but SQLiteAdapter is also supported.

    You can also provide lifecycle callbacks: onConnecting, onConnected, and onDisconnected.

    import { Whatsapp, RedisAdapter } from "wa-multi-session";
    
    const whatsapp = new Whatsapp({
      adapter: new RedisAdapter({
        url: "redis://localhost:6379",
      }),
    
      // Optional: Add Listener/Callback
      onConnecting: (sessionId) => {
        console.log(`[${sessionId}] Connecting...`);
      },
      onConnected: (sessionId) => {
        console.log(`[${sessionId}] Connected`);
      },
      onDisconnected: (sessionId) => {
        console.log(`[${sessionId}] Disconnected`);
      },
    });
  3. Configure Adapter options

    master

    Adapters can be customized during initialization:

    • RedisAdapter: Supports a url for the connection and a keyPrefix to namespace keys in Redis.
    • SQLiteAdapter: Supports a databasePath to specify where the .db file is stored.
    // Redis with custom prefix
    const adapter = new RedisAdapter({
      url: "redis://localhost:6379",
      keyPrefix: "my_app:",
    });
    
    // SQLite with custom path
    const adapter = new SQLiteAdapter({
      databasePath: "my_custom_dir/database.db",
    });
  4. Initialize the Whatsapp class

    master

    To use the library, instantiate the Whatsapp class. You must provide an adapter (to handle session persistence) and can optionally specify a debugLevel. If autoLoad is set to true (default), the class will automatically attempt to restart all existing sessions found in the adapter upon initialization.

    import { Whatsapp } from './path-to-library';
    
    const whatsapp = new Whatsapp({
      adapter: myAdapter, // Must implement the Adapter interface
      debugLevel: 'info', // Optional: 'silent', 'error', 'warn', 'info', 'debug'
      autoLoad: true     // Optional: defaults to true
    });
  5. Send various message types

    master

    The Whatsapp instance provides several methods to send messages. Most methods require a sessionId and a to recipient (phone number).

    • sendText: Sends a plain text message. Use answering to quote a message.
    • sendImage: Sends an image (Buffer or URL) with an optional text caption.
    • sendVideo: Sends a video (Buffer or URL) with an optional text caption.
    • sendDocument: Sends a file. Requires filename and media (Buffer or URL).
    • sendAudio: Sends audio. Use asVoiceNote: true to send as a PTT (push-to-talk) message.
    • sendPoll: Sends a poll with name, values (array), and selectableCount.
    • sendTypingIndicator: Triggers a typing effect for a specified duration (ms).
    • readMessage: Marks a message as read.
    // Send Text
    await whatsapp.sendText({
      sessionId: "session1",
      to: "6281234567890",
      text: "Hi There!",
    });
    
    // Send Image
    const image = fs.readFileSync("./myimage.png");
    await whatsapp.sendImage({
      sessionId: "session1",
      to: "6281234567890",
      text: "My Image Caption",
      media: image,
    });
    
    // Send Poll
    await whatsapp.sendPoll({
      sessionId: "session1",
      to: "6281234567890",
      poll: {
        name: "Your favorite programming language?",
        values: ["JavaScript", "Python", "Go", "Rust"],
        selectableCount: 1,
      },
    });
  6. Manage WhatsApp sessions

    master

    You can manage multiple WhatsApp sessions using the following methods:

    • startSession(sessionId, options): Starts a new session. Use { printQR: true } to display the QR code in the terminal.
    • startSessionWithPairingCode(sessionId, options): (Experimental) Starts a session using a phone number and pairing code. Requires phoneNumber and an onPairingCode callback.
    • getSessionsIds(): Returns an array of all created session IDs.
    • getSessionById(sessionId): Returns the data for a specific session.
    // Start New Session with QR Code
    const session = await whatsapp.startSession("session1", {
      printQR: true,
    });
    
    // Start Session with Pairing Code (Experimental)
    const session = await whatsapp.startSessionWithPairingCode("mysessionid", {
      phoneNumber: "6281234567890",
      onPairingCode(code) {
        console.log(`Pairing Code: ${code}`);
      },
    });
    
    // Get All Session IDs
    const sessions = await whatsapp.getSessionsIds();
    
    // Get Session Data By ID
    const session = await whatsapp.getSessionById("session1");
  7. Retrieve all active session IDs via getSQLiteSessionIds

    master

    Use getSQLiteSessionIds to retrieve an array of all unique session_id values currently stored in the SQLite auth_store table. This allows you to list all active WhatsApp sessions managed by the application.

    import { getSQLiteSessionIds } from 'wa-multi-session/src/Store/Sqlite';
    
    const sessionIds = await getSQLiteSessionIds();
    console.log('Active sessions:', sessionIds);
  8. Send text messages

    master

    Send a text message to a user or group using sendText. The to field should be a phone number string, and isGroup determines the target type.

    await whatsapp.sendText({
      sessionId: 'my-session-id',
      to: '1234567890',
      isGroup: false,
      text: 'Hello, this is a test message!',
      answering: someMessageKey // Optional: to reply to a specific message
    });
  9. Configure session initialization with StartSessionWithPairingCodeParams

    master

    Use StartSessionWithPairingCodeParams when you want to connect via a phone number and pairing code instead of scanning a QR code.

    Required field:

    • phoneNumber: The phone number including the country code.

    Available event handlers:

    • onPairingCode: Triggered when the pairing code is generated.
    • onQRUpdated, onConnected, onConnecting, onDisconnected, onMessageReceived, onMessageUpdated: Same as StartSessionParams.
    • store: Optional LegacyStore for session persistence.
    const params: StartSessionWithPairingCodeParams = {
      phoneNumber: '861234567890',
      onPairingCode: (code) => console.log('Your pairing code is:', code),
      onConnected: () => console.log('Connected via pairing code!')
    };
  10. Send documents with `sendDocument`

    master

    Use sendDocument to send files like PDFs or other documents. Unlike other media functions, you must provide a filename string. The function will automatically determine the mimetype based on the file extension.

    await sendDocument({
      sessionId: 'my-session',
      to: '1234567890',
      media: documentBuffer,
      filename: 'report.pdf',
      text: 'Here is the report',
      isGroup: false
    });
  11. Send media messages (Image, Video, Document, Audio, Sticker)

    master

    The library provides specialized methods for different media types. For most methods, media can be either a local file path/buffer or a URL string.

    // Send Image
    await whatsapp.sendImage({
      sessionId: 'my-session-id',
      to: '1234567890',
      isGroup: false,
      media: 'https://example.com/image.jpg',
      text: 'Check this out!'
    });
    
    // Send Document (requires filename for mimetype detection)
    await whatsapp.sendDocument({
      sessionId: 'my-session-id',
      to: '1234567890',
      isGroup: false,
      media: './files/report.pdf',
      filename: 'report.pdf',
      text: 'Here is your file'
    });
    
    // Send Audio as Voice Note
    await whatsapp.sendAudio({
      sessionId: 'my-session-id',
      to: '1234567890',
      isGroup: false,
      media: './audio.mp3',
      asVoiceNote: true
    });