WhatsApp Bot Utilities for Baileys

raw JSON →
10.10.2 verified Thu Apr 23 auth: no javascript

This library, `utils-mf`, provides a collection of helper functions designed to streamline the development of WhatsApp bots using the `@adiwajshing/baileys` package. It abstracts away common tasks such as initializing the WhatsApp client, handling media (sending and downloading), message serialization, querying group information, and retrieving contact details. Additionally, it offers various general-purpose utilities like URL validation, time formatting, and random number generation, and its keywords suggest integration for TikTok media downloading. Currently at version `10.10.2`, the package appears to be actively maintained, indicated by a healthy release cadence. It is primarily distributed as a CommonJS module. Its main value lies in offering a convenient toolkit for developers working with the unofficial WhatsApp Web API via Baileys, aiming to simplify complex bot functionalities.

error ReferenceError: require is not defined
cause Attempting to use `require()` in an ES Module context, or `import` in a CommonJS context without proper configuration. `utils-mf` is a CommonJS module.
fix
If your project is ESM, either switch to CommonJS by removing "type": "module" from package.json or use dynamic import: const { start } = await import('utils-mf');. If your project is CommonJS, use const { start } = require('utils-mf');.
error Error: Cannot find module '@adiwajshing/baileys'
cause The core dependency `@adiwajshing/baileys` is not installed or incorrectly resolved.
fix
Ensure @adiwajshing/baileys is listed in your package.json dependencies and run npm install or yarn install.
error (node:XXXX) UnhandledPromiseRejectionWarning: Error: connect ECONNREFUSED
cause This usually indicates an issue connecting to WhatsApp's servers, which can be due to network problems, WhatsApp server-side issues, or the bot session being detected and terminated by WhatsApp for violating terms of service.
fix
Check your internet connection. Try restarting the bot. If persistent, this might be a sign of a temporary ban or detection of unofficial API usage. Monitor WhatsApp status. Consider implementing robust reconnection logic with exponential backoff.
breaking Relying on unofficial WhatsApp APIs (like Baileys) is against WhatsApp's Terms of Service and can lead to frequent disconnections, 401 errors, or permanent account bans. WhatsApp actively detects and kills unofficial bridge sessions.
fix For critical business operations, consider migrating to the official WhatsApp Business API, which offers dedicated support and adheres to Meta's policies, despite having per-conversation pricing and requiring a dedicated phone number.
gotcha This package is distributed as a CommonJS module (`"type": "commonjs"` in its `package.json`). Attempting to use `import` statements directly in an ES Module Node.js project will result in a `SyntaxError: Cannot use import statement outside a module`.
fix Ensure your project is configured for CommonJS, or use dynamic `import()` if you must use it within an ESM context: `const { start } = await import('utils-mf');`. The primary method should be `const { start } = require('utils-mf');`.
deprecated The underlying `@adiwajshing/baileys` library has undergone significant API changes across major versions (e.g., v5 to v6). `utils-mf` may not be compatible with all Baileys versions, potentially leading to unexpected behavior or breakage if Baileys is updated independently.
fix Always align the `baileys` version used with the specific version `utils-mf` was built against. Check `utils-mf`'s `package.json` to verify the compatible Baileys range. Pin dependency versions to avoid automatic, potentially breaking updates.
gotcha Supply chain attacks targeting WhatsApp API packages are a known risk in the npm ecosystem. Malicious packages have masqueraded as legitimate ones, stealing credentials, messages, and contacts.
fix Exercise extreme caution when installing or updating any packages related to unofficial WhatsApp APIs. Vet dependencies thoroughly, use npm audit, and consider tools that analyze package contents for suspicious activity. Regularly revoke WhatsApp sessions linked to bots.
npm install utils-mf
yarn add utils-mf
pnpm add utils-mf

Demonstrates initializing a basic WhatsApp bot using `utils-mf` with `@adiwajshing/baileys`, connecting, and responding to "hello" messages and sending media upon "media" command.

const { start, sendMedia, sleep } = require('utils-mf');
const { WA_DEFAULT_EPHEMERAL } = require('@adiwajshing/baileys');

// Basic example of how to start a WhatsApp bot and handle messages
async function main() {
  console.log('Starting WhatsApp bot...');

  // Initialize Baileys client through utils-mf's start function
  const { client, store } = await start({
    sessionName: 'my-bot-session', // Name for your session file
    pairingCode: process.env.PAIRING_CODE, // Optional: for pairing code login, provide as env var
    qr: true, // Show QR code in terminal for login
    logger: console, // Use console for logging
    browser: ['Chrome (Linux)', '', ''] // Browser info for Baileys
  });

  // Handle connection updates (e.g., reconnect on disconnect)
  client.ev.on('connection.update', (update) => {
    const { connection, lastDisconnect } = update;
    if (connection === 'close') {
      const shouldReconnect = lastDisconnect?.error?.output?.statusCode !== 401; // 401 means session invalidated
      console.log('connection closed due to ', lastDisconnect?.error, ', reconnecting ', shouldReconnect);
      if (shouldReconnect) {
        main(); // Attempt to reconnect
      }
    } else if (connection === 'open') {
      console.log('Opened connection!');
    }
  });

  // Handle incoming messages
  client.ev.on('messages.upsert', async (m) => {
    const msg = m.messages[0];
    // Only process messages not from ourselves and of type 'notify' (actual messages)
    if (!msg.key.fromMe && m.type === 'notify') {
      const jid = msg.key.remoteJid; // Sender's JID
      // Extract message text from different message types
      const text = msg.message?.conversation || msg.message?.extendedTextMessage?.text || '';

      if (text.toLowerCase() === 'hello') {
        await client.sendMessage(jid, { text: 'Hello from utils-mf bot!' }, { ephemeralExpiration: WA_DEFAULT_EPHEMERAL });
        console.log(`Sent "Hello" to ${jid}`);
      } else if (text.toLowerCase() === 'media') {
        const imageUrl = 'https://picsum.photos/200/300'; // Example image URL
        // Use sendMedia from utils-mf to send an image
        await sendMedia(client, jid, imageUrl, 'image', 'Here is a random image!');
        console.log(`Sent media to ${jid}`);
      }
    }
  });

  console.log('Bot is running. Scan QR if needed or waiting for messages.');
}

main().catch(err => console.error("Bot error:", err));