skip to Main Content

I would like to send messages every 5 seconds on differents numbers with this code:

const send_message = ["34123456789","34123456789","34123456789"];

client.on("ready", () => {
   console.log("Client is ready!");
   send_message.map((value) => {
     const chatId = value + "@c.us";
     const message = 'This is a test message';

     client.sendMessage(chatId, message);
   });
});

Where or how can I add this code to create a correct bucle?

await sleep(5000);

2

Answers


  1. use a for…of loop instead and make the client.on callback async

    Something like

    const send_message = ["34123456789", "34123456789", "34123456789"];
    
    client.on("ready", async () => {
      console.log("Client is ready!");
    
      for (value of send_message) {
        const chatId = value + "@c.us";
        const message = 'This is a test message';
        client.sendMessage(chatId, message);
        await sleep(5000);
      }
    });
    
    Login or Signup to reply.
  2. You can use await only in an async context. So you can do like this for instance, using for .. of instead of map

    client.on("ready", async () => {
      for (let value of send_message) {
        const chatId = value + "@c.us";
        const message = 'This is a test message';    
        client.sendMessage(chatId, message);
        await sleep(5000);
      }
    })
    

    BTW since node 16 you don’t need to create your own sleep (or similar) method anymore. You can use setTimeout from the timers/promises module

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search