1

I am making a WhatsApp bot using WhatsApp Web.js, and I am sending bulk messages to my contact.

I have saved numbers in number.js but I want to add a delay in foreach to avoid getting banned by WhatsApp, but it only works one time.

There are two numbers in my array, there should be a 20 second delay between them, but there is only a delay while sending the first message. Then, both messages are sent together.

All help is appreciated.

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();
Wongjn
  • 8,544
  • 2
  • 8
  • 24
burst is live
  • 47
  • 1
  • 6
  • Assuming `Numbers` is an array, then `Array.forEach` does not support async callbacks ... – derpirscher May 06 '23 at 12:30
  • Does this answer your question? [Using async/await with a forEach loop](https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop) – derpirscher May 06 '23 at 12:30

1 Answers1

1

Array methods, be default (se further info below) does not support async functions, so the easiest solution is to replace your forEach with a for...of-loop an make your smsg function async:

const smsg = async () => {

    for(let item of Numbers){ ...do async stuff, await...

However you can make array methods like forEach (and map, reduce, every etc) support async, I've written an answer about that here:

Best way to call an asynchronous function within map?

Thomas Frank
  • 1,404
  • 4
  • 10
  • Please do not answer questions that have been answered multiple times already, but flag them as duplicte ... – derpirscher May 06 '23 at 12:44
  • Thanks for anyone wondering this how my chode looks like now `const smsg = async () => { for (let item of Numbers) { let final_num = item.substring(1); let currnum = 1; let count = currnum;` – burst is live May 07 '23 at 02:14