NodeJS 每“x”秒发送一次消息

vbopmzt1  于 2023-06-05  发布在  Node.js
关注(0)|答案(2)|浏览(234)

我想每隔5秒发送一次消息到不同的号码,代码如下:

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);
   });
});

在哪里或如何添加此代码以创建正确的bucle?

await sleep(5000);
raogr8fs

raogr8fs1#

使用for...of循环代替,并使客户端.on回调async
就像

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

client.on("ready", async () => {
  console.log("Client is ready!");

  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);
  }
});
hgc7kmma

hgc7kmma2#

您只能在异步上下文中使用await。例如,您可以这样做,使用for .. 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);
  }
})

顺便说一句,从节点16开始,你不再需要创建自己的sleep(或类似的)方法了。可以从timers/promises模块使用setTimeout

相关问题