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

@iamrony777/baileys

v6.7.7-1

Published

WhatsApp API

Downloads

57

Readme

Baileys - Typescript/Javascript WhatsApp Web API

About this Fork

The original repository was removed by its author and later taken over by WhiskeySockets. This current fork is based on that. I've only made additions such as custom stores for storing authentication, messages, etc., and merged a few pull requests. That's all.

If you encounter any issues after using this fork or any part of it, I recommend creating a new issue here rather than on WhiskeySocket's Discord server. AND EXPECT BUGS, LOTS OF BUGS (THIS IS UNSTABLE ASF)

NPM Package

Installation

Check .env.example first to setup databases

yarn install @iamrony777/baileys

or

yarn github:iamrony777/Baileys ## Directly from github repo

Then import your code using:

import makeWASocket, { ... } from '@iamrony777/baileys'

Connecting multi device (recommended)

I recommend to use Redis for storing auth data (as it is the fastest) and Mongo for storing chats, messages

WhatsApp provides a multi-device API that allows Baileys to be authenticated as a second WhatsApp client by scanning a QR code with WhatsApp on your phone.

import { MongoClient } from "mongodb";
import makeWASocket, {
  DisconnectReason,
  makeCacheableSignalKeyStore,
  makeMongoStore,
  useMongoDBAuthState,
} from "@iamrony777/baileys";
import { Boom } from "@hapi/boom";
import "dotenv/config";

async function connectToWhatsApp() {
  // MongoDB setup
  const mongo = new MongoClient(process.env.MONGODB_URL!, {
    socketTimeoutMS: 1_00_000,
    connectTimeoutMS: 1_00_000,
    waitQueueTimeoutMS: 1_00_000,
  });
  const authCollection = mongo.db("wpsessions").collection("auth");
  const { state, saveCreds } = await useMongoDBAuthState(authCollection);
  const store = makeMongoStore({ db: mongo.db("wpsessions"), autoDeleteStatusMessage: true });

  const sock = makeWASocket({
    auth: {
      creds: state.creds,
      /** caching makes the store faster to send/recv messages */
      keys: makeCacheableSignalKeyStore(state.keys),
    },

    // can provide additional config here
    printQRInTerminal: true,
  });

  // listen on events and update database
  store.bind(sock.ev);

  sock.ev.on("connection.update", async (update) => {
    const { connection, lastDisconnect } = update;
    if (connection === "close") {
      const shouldReconnect =
        (lastDisconnect?.error as Boom)?.output?.statusCode !==
        DisconnectReason.loggedOut;
      console.log(
        "connection closed due to ",
        lastDisconnect?.error,
        ", reconnecting ",
        shouldReconnect
      );
      // reconnect if not logged out
      if (shouldReconnect) {
        await mongo.close();
        connectToWhatsApp();
      }
    } else if (connection === "open") {
      console.log("opened connection");
      await sock.sendMessage(
        sock.user?.id!,
        {
          text: "Connected!",
        },
        { ephemeralExpiration: 1 * 60 }
      );
    }
  });

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

    // if message type is notify and not a protocol message
    if (
      m.type === "notify" &&
      !m.messages[0].message?.hasOwnProperty("protocolMessage")
    ) {
      console.log("replying to", m.messages[0].key.remoteJid);

      // await sock.sendMessage(m.messages[0].key.remoteJid!, {
      //   text: "Hello there!",
      // });
    }
  });

  sock.ev.on("creds.update", async () => {
    await saveCreds();
  });
}
// run in main file
connectToWhatsApp();

If the connection is successful, you will see a QR code printed on your terminal screen, scan it with WhatsApp on your phone and you'll be logged in!

Note: install qrcode-terminal using yarn add qrcode-terminal to auto-print the QR to the terminal.

Note: the code to support the legacy version of WA Web (pre multi-device) has been removed in v5. Only the standard multi-device connection is now supported. This is done as WA seems to have completely dropped support for the legacy version.

Note: I didn't add the search-by-contact-hash implementation by purpshell

Custom funtions added to this package

1. store?.getContactInfo(jid: string, socket: typeof makeWASocket)

if (events["contacts.update"]) {
  for (const update of events["contacts.update"]) {
    if (update.imgUrl === "changed") { // getting 
      const contact = await store?.getContactInfo(update.id!, sock);
      console.log(
        `contact ${contact?.name} ${contact?.id} has a new profile pic: ${contact?.imgUrl}`
      );
    }
  }
}

Everything besides store and auth connectors are same as the original repo.

Read here