WhatsApp Bot Utilities for Baileys
raw JSON →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.
Common errors
error ReferenceError: require is not defined ↓
"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' ↓
@adiwajshing/baileys is listed in your package.json dependencies and run npm install or yarn install. error (node:XXXX) UnhandledPromiseRejectionWarning: Error: connect ECONNREFUSED ↓
Warnings
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. ↓
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`. ↓
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. ↓
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. ↓
Install
npm install utils-mf yarn add utils-mf pnpm add utils-mf Imports
- start, sendMedia wrong
import { start } from 'utils-mf';correctconst { start, sendMedia } = require('utils-mf'); - downloadMedia, serialize wrong
const download = require('utils-mf').downloadMedia;correctconst { downloadMedia, serialize } = require('utils-mf'); - All exports (e.g., when exploring) wrong
import * as utilsMf from 'utils-mf';correctconst utilsMf = require('utils-mf');
Quickstart
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));