Back

Technologies:

javascriptjavascript
node.jsnode.js
avatar
Tolerim
21 hours ago

How do I ensure the delay works only once in a foreach loop using whatsapp.js?

As I develop a WhatsApp bot with WhatsApp Web.js, I am sending bulk messages to my contacts. Although I have saved the numbers in "number.js," I need to introduce a delay in "foreach" to avoid being banned by WhatsApp. Unfortunately, it only works once, meaning there is a delay while sending the first message, and after that, both messages are sent together. I would appreciate any assistance. Here is the sample code:
const sleep = ms => new Promise(r => setTimeout(r, ms))

const smsg = () => {

    Numbers.forEach(async (item) => {



        let final_num = item.substring(1);
        let currnum = 1;
        let count = currnum;

        const messagetosend = "hello";
        let getuser = await user.getNumberId(final_num);
        if (getuser) {
            
            await sleep(20000)
            var newn = count + 1
            let currnum = newn
            console.log(currnum)
            console.log('Message sent to ' + final_num)
            const msg = await user.sendMessage(getuser._serialized, messagetosend)
            

        }
        else { console.log("Number not found") };

    })

}
user.on('message', message => {
    if (message.body === '!start 2005') {
        smsg()
    }
});


user.initialize();
Answers(1)
avatar
Tolerim
21 hours ago
Verified Answer
To add a delay between each message being sent in a forEach loop, you can use the async/await syntax to ensure that each message is sent only after the previous message has been sent and the specified time delay has elapsed. In the given code snippet, the forEach loop is already using the async keyword, which means that each iteration of the loop will return a promise. To add a delay between each iteration, you can use the await keyword followed by the sleep function that takes a specified time delay in milliseconds. Here's an updated code snippet that should add a 20 second delay between each message being sent:
const sleep = ms => new Promise(r => setTimeout(r, ms));

const smsg = async () => {
  for (const item of Numbers) {
    let final_num = item.substring(1);
    let count = Numbers.indexOf(item) + 1;

    const messagetosend = "hello";
    let getuser = await user.getNumberId(final_num);
    if (getuser) {
      console.log('Message sent to ' + final_num);
      const msg = await user.sendMessage(getuser._serialized, messagetosend);
      await sleep(20000);
    } else {
      console.log("Number not found");
    }
  }
};

user.on('message', message => {
  if (message.body === '!start 2005') {
    smsg();
  }
});

user.initialize();
The smsg function has been updated to use a for-of loop instead of a forEach loop, since it allows the use of the await keyword inside the loop. The count variable has also been updated to use Numbers.indexOf(item) + 1 to get the current index of the number being processed. Inside the loop, the message is sent and then a delay of 20 seconds is added by calling the sleep function with a delay of 20000 milliseconds (20 seconds) using await sleep(20000). This ensures that the loop will wait for the delay to complete before moving on to the next iteration.
;