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

如何在Render上部署whatsapp-web.js自动回复机器人?端口绑定问题

解决WhatsApp机器人部署到Render的端口绑定问题

你的问题核心是Render的Web服务要求应用必须绑定一个公开可访问的端口(监听0.0.0.0),但当前代码未启动任何HTTP服务器,导致Render检测不到开放端口,无法正常运行服务。

解决方案:添加简易HTTP服务器

无需使用Express,用Node.js内置的http模块就能快速创建满足Render要求的服务器,同时保留机器人原有逻辑。

修改后的代码如下:

const http = require('http');
const mongoose = require('mongoose');
const { Client } = require('whatsapp-web.js');

// 创建基础HTTP服务器,用于响应Render的健康检查
const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('WhatsApp自动回复机器人已运行\n');
});

const startApp = async () => {
    if (!process.env.MONGODB_URI) {
        console.error("Error: MONGODB_URI environment variable is not set.");
        process.exit(1);
    }
    try {
        await mongoose.connect(process.env.MONGODB_URI);
        console.log("Connected to MongoDB");
        
        // 启动HTTP服务器,绑定Render提供的端口与公开地址
        const PORT = process.env.PORT || 3000;
        server.listen(PORT, '0.0.0.0', () => {
          console.log(`HTTP服务器运行在端口 ${PORT}`);
        });

        await client.initialize();
        console.log("WhatsApp Client initialized");
    } catch (error) {
        console.error("Error starting the app:", error);
        process.exit(1);
    }
};

startApp();

关键细节说明:

  • 端口配置:Render会自动分配PORT环境变量,代码中通过process.env.PORT获取,同时指定监听地址为0.0.0.0,确保Render能检测到开放端口。
  • HTTP服务器作用:仅用于响应Render的健康检查请求,无需复杂路由,保证服务不会被判定为未启动。
  • 会话持久化:你已通过MongoDB存储会话,首次部署需扫码登录(可借助whatsapp-web.js的远程扫码功能,或本地登录后同步会话到MongoDB),后续重启会自动恢复会话状态。

部署后Render即可检测到开放端口,机器人的自动回复功能就能正常运行。

内容的提问来源于stack exchange,提问作者Emuemhonjie Onosereme

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 11:33:21