You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Wa Web JS页面刷新后重复发送消息问题求助

解决WhatsApp Web JS集成Express后刷新页面重复发送消息的问题

问题情况

在Express模板中集成WhatsApp Web JS的二维码功能,首次运行正常,但刷新页面更换二维码后,消息发送次数会随刷新次数增加。例如刷新两次,数组内的号码会收到两次重复消息。

刷新两次后的控制台输出:

Client is ready!
Sending messages...
Client is ready!
Sending messages...

问题根源

  • 每次访问/qrcode路由时,都会重复给client实例注册ready事件回调(即便用了once,每个请求注册的回调都会在client就绪时触发一次)。
  • 每次请求都调用client.initialize(),导致client重复初始化,触发多次ready事件。

解决方案

将client的事件注册、初始化逻辑移到路由外部仅执行一次,同时添加全局标志位控制消息仅发送一次。

修改后的后端代码

// 全局标志位:标记消息是否已发送
let messagesSent = false;
// 全局存储当前生成的二维码
let currentQr = null;

// 全局注册client事件,仅执行一次
client.on('qr', qr => {
  currentQr = qr;
});

client.once('ready', async () => {
  console.log('Client is ready!');
  
  // 仅在消息未发送时执行发送逻辑
  if (!messagesSent) {
    console.log('Sending messages...');
    const nomer_telephone = ["+6281932240030", "+6281932240030","+6281932240030"];
    const textId = `Assalamualaikum Wr.wb`; 

    for (const nomor of nomer_telephone) {
      const chatId = nomor.substring(1) + "@c.us"; 
      await client.sendMessage(chatId, textId); // 添加await确保消息发送顺序
    }
    messagesSent = true;
  }
});

// 仅初始化一次client
client.initialize();

// 路由仅负责返回当前二维码
app.get('/qrcode', async (req, res) => {
  if (!currentQr) {
    return res.send('等待二维码生成...');
  }
  QRCode.generate(currentQr, { small: true, width: 8000 }, (qrcode) => {
    res.render("qrcode", {
      qr: qrcode
    });
  });
});

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

关键调整说明

  • 把qr、ready事件的监听逻辑移到路由外部,确保仅注册一次,避免重复触发。
  • 使用messagesSent全局变量,确保ready事件触发时消息只发送一次。
  • client.initialize()仅执行一次,避免重复初始化导致多次触发ready事件。
  • 消息发送循环添加await,保证每条消息发送完成后再执行下一条,避免发送混乱。

内容的提问来源于stack exchange,提问作者moza achmad dani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 20:32:28