How to add participants to a WhatsApp group using whatsapp-web.js

I made a video explaining how to do Whatsapp automation using Javascript. Someone has asked this question in the comments of that video asking about how to add participants to a WhatsApp group using whatsapp-web.js Let’s find out!

Example source code

Here’s the example source code to add participants to a group using Whatsapp API

const { Client, LocalAuth } = require("whatsapp-web.js");
const qrcode = require("qrcode-terminal");

const myGroupName = "Group Name";
const contactName = "John Doe";

const client = new Client({
  authStrategy: new LocalAuth(),
});

client.on("qr", (qr) => {
  qrcode.generate(qr, { small: true });
});

client.on("ready", () => {
  console.log("Client is ready!");
  client.getChats().then((chats) => {
    const myGroup = chats.find((chat) => chat.name === myGroupName);
    client.getContacts().then((contacts) => {
      const contactToAdd = contacts.find(
        // Finding the contact Id using the contact's name
        (contact) => contact.name === contactName
      );
      if (contactToAdd) {
        myGroup
          .addParticipants([contactToAdd.id._serialized]) // Pass an array of contact IDs [id1, id2, id3 .....]
          .then(() =>
            console.log(
              `Successfully added ${contactName} to the group ${myGroupName}`
            )
          );
      } else {
        console.log("Contact not found");
      }
    });
  });
});

client.initialize();

Adding participants using phone number

All we need to do is pass a list of contact IDs to addParticipants method.

In this example, I’m finding the contact ID using the contact’s name but you can directly pass the contact ID if you already have the phone number of the contact.

contact ID will be in this format – [email protected]c.us

91 is the country code of India. Replace it with your country code. Replace the remaining part with the actual phone number. @c.us remains the same for all contacts in all countries.

If you are passing IDs directly then the code would look something like this:

myGroup.addParticipants(["[email protected]", "[email protected]"])
5 1 vote
Article Rating
Subscribe
Notify of
guest
2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Athxl
12 days ago

Please show me how to get group info like group name, group description using whatsapp web js