npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

mongo-baileys

v1.0.1

Published

Save your baileys session in mongodb using this package

Downloads

216

Readme

mongo-baileys 🚀💾

License: MIT npm version npm downloads

✨ Elevate your WhatsApp bot's reliability with seamless MongoDB session persistence! ✨

mongo-baileys is a powerful Node.js library that empowers your Baileys-powered WhatsApp bots with the ability to store and retrieve session data in MongoDB. This ensures your bot stays connected even after restarts, making it more resilient and user-friendly.

✨ Why Choose mongo-baileys?

  • Persistence: Never lose your bot's session again, even after server restarts or crashes.
  • Reliability: Automatic reconnects handle disconnections gracefully, ensuring your bot is always online.
  • TypeScript: Enjoy the benefits of static typing and improved code maintainability with TypeScript support.
  • Effortless Integration: Seamlessly integrate mongo-baileys into your existing Baileys projects with minimal changes.
  • Customization: Tailor the library to your specific needs with flexible configuration options.

📦 Installation

npm install mongo-baileys

🛠️ Usage

JavaScript

import { MongoClient } from 'mongodb';
import { makeWASocket, AnyMessageContent } from '@whiskeysockets/baileys';
import { useMongoDBAuthState } from 'mongo-baileys';
import Boom from '@hapi/boom';

const url = "YOUR_MONGODB_URL"; // Replace with your MongoDB connection string // When Obtaining Mongodb URL Choose NodeJS Driver Version 2 or Later but don't 3 or it higher
const dbName = "whatsapp";
const collectionName = "authState";

async function connectToMongoDB() {
    const client = new MongoClient(url);
    await client.connect();
    const db = client.db(dbName);
    const collection = db.collection(collectionName);
    return { client, collection };
}

async function startWhatsApp() {
    const { collection } = await connectToMongoDB();
    const { state, saveCreds } = await useMongoDBAuthState(collection);

    const sock = makeWASocket({
        auth: state,
        printQRInTerminal: true,
    });

    sock.ev.on('creds.update', saveCreds);

    sock.ev.on('connection.update', (update) => {
        const { connection, lastDisconnect } = update;
        if (connection === 'close') {
            const shouldReconnect = lastDisconnect && lastDisconnect.error
                ? Boom.boomify(lastDisconnect.error).output.statusCode
                : 500;
            console.log('Connection closed due to', lastDisconnect?.error, ', reconnecting in', shouldReconnect, 'ms');
            if (shouldReconnect) {
                setTimeout(() => startWhatsApp(), shouldReconnect);
            }
        } else if (connection === 'open') {
            console.log('Opened connection');
        }
    });

    sock.ev.on('messages.upsert', async (m) => {
        console.log(JSON.stringify(m, null, 2));

        const message = m.messages[0];
        if (message && !message.key.fromMe && m.type === 'notify') {
            console.log('Replying to', message.key.remoteJid);
            await sock.sendMessage(message.key.remoteJid, { text: 'Hello there!' });
        }
    });

    // Graceful shutdown
    process.on('SIGINT', async () => {
        console.log('Received SIGINT. Closing connection...');
        await sock.close();
        process.exit();
    });

    process.on('SIGTERM', async () => {
        console.log('Received SIGTERM. Closing connection...');
        await sock.close();
        process.exit();
    });
}

startWhatsApp().catch(err => console.error("Unexpected error:", err));

TypeScript

import { MongoClient, Collection, Document } from "mongodb";
import { makeWASocket, AnyMessageContent } from '@whiskeysockets/baileys';
import { useMongoDBAuthState } from 'mongo-baileys';
import * as Boom from '@hapi/boom';
import { AuthenticationCreds } from "@whiskeysockets/baileys";

const url = "YOUR_MONGODB_URL"; // When Obtaining Mongodb URL Choose NodeJS Driver Version 2 or Later but don't 3 or it higher
const dbName = "whatsapp";
const collectionName = "authState";

interface AuthDocument extends Document {
    _id: string;
    creds?: AuthenticationCreds;
}

async function connectToMongoDB() {
    const client = new MongoClient(url);
    await client.connect();
    const db = client.db(dbName);
    const collection = db.collection<AuthDocument>(collectionName);
    return { client, collection };
}

async function startWhatsApp() {
    const { collection } = await connectToMongoDB();
    const { state, saveCreds } = await useMongoDBAuthState(collection);


    const sock = makeWASocket({
        auth: state,
        printQRInTerminal: true,
    });

    sock.ev.on('creds.update', saveCreds);

    sock.ev.on('connection.update', (update) => {
        const { connection, lastDisconnect } = update;
        if (connection === 'close') {
            const shouldReconnect = lastDisconnect && lastDisconnect.error
                ? Boom.boomify(lastDisconnect.error).output.statusCode
                : 500;
            console.log('Connection closed due to', lastDisconnect?.error, ', reconnecting in', shouldReconnect, 'ms');
            if (shouldReconnect) {
                setTimeout(() => startWhatsApp(), shouldReconnect);
            }
        } else if (connection === 'open') {
            console.log('Opened connection');
        }
    });

    sock.ev.on('messages.upsert', async (m) => {
        console.log(JSON.stringify(m, undefined, 2));

        const message = m.messages[0];
        if (message && !message.key.fromMe && m.type === 'notify') {
            console.log('Replying to', message.key.remoteJid);
            await sock.sendMessage(message.key.remoteJid!, { text: 'Hello there!' } as AnyMessageContent);
        }
    });
}

startWhatsApp().catch(err => console.log("Unexpected error:", err));

🤝 Contributing

Contributions are welcome! Feel free to open issues and submit pull requests to enhance mongo-baileys.