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

Discord机器人实时输出无法在网页展示,求助Express问题排查

Discord机器人实时输出网页展示问题排查与解决

需求是将Discord机器人的实时消息输出展示在网页上,当前使用Express.js搭建服务器、JavaScript开发Discord机器人,但始终无法实现实时展示。此前用Python开发Bot也未成功,以下是问题梳理与修正方案:


原代码核心问题梳理

Bot代码问题

  1. 库导入错误:Node.js中Discord机器人的正确依赖是discord.js,而非discord;且不存在discord.ext模块(这是Python版discord.py的语法),需使用discord.js的Client类。
  2. 事件监听方法错误:Discord.js v14+中,消息事件应为messageCreate,而非client.listen。
  3. 权限意图缺失:默认Intents.default()不包含MessageContent意图,必须手动添加,且需在Discord开发者后台开启该权限,否则无法读取消息内容。
  4. 请求发送格式错误:requests库在Node.js中的调用逻辑有误,未正确发送JSON数据,也未处理异常;建议改用axios或原生fetch。
  5. 变量名错误:帮助命令中循环的commands变量未定义,实际应为availableCommands。

服务器代码问题

  1. 未解析JSON请求体:Express默认不会解析JSON格式的POST请求,需添加app.use(express.json()),否则req.body为undefined。
  2. 全局变量未声明:terminalOutput未用let/const声明,会成为全局变量,且无初始值,需初始化。
  3. 输出内容固定:getTerminalOutput函数始终返回固定字符串,未返回实际接收的机器人消息。

网页代码问题

  1. 内容覆盖而非追加:每次请求后直接替换innerHTML,会丢失历史消息,应改为追加内容。
  2. 轮询逻辑冗余:当前1秒轮询会产生不必要的请求,可优化为仅在内容变化时更新DOM。

修正后的代码

1. Discord机器人代码(先执行npm install discord.js axios安装依赖)

const { Client, GatewayIntentBits } = require('discord.js');
const axios = require('axios');

// 初始化客户端,必须包含消息内容读取权限
const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent
  ]
});

// 可用命令列表
const availableCommands = ["!hello", "!goodbye", "!help"];

// 监听消息创建事件
client.on('messageCreate', async (message) => {
  // 忽略机器人自身发送的消息
  if (message.author.bot) return;

  // 处理命令
  if (message.content.startsWith('!hello')) {
    await message.channel.send('Hello!');
  } else if (message.content.startsWith('!goodbye')) {
    await message.channel.send('Goodbye!');
  } else if (message.content.startsWith('!log')) {
    console.log('收到!log命令');
  } else if (message.content.startsWith('!help')) {
    let response = "Commands:\n";
    for (const command of availableCommands) {
      response += `${command}\n`;
    }
    response += "\nBot made by Agent_12";
    await message.channel.send(response);
  }

  // 将消息发送到Express服务器
  try {
    await axios.post('http://localhost:3000/terminal-output', {
      output: `[${message.author.tag}] ${message.content}`
    });
  } catch (error) {
    console.error('发送消息到服务器失败:', error.message);
  }
});

// 启动机器人,替换为你的Bot Token
client.login('你的Discord机器人Token');

2. Express服务器代码(先执行npm install express安装依赖)

const express = require('express');
const app = express();

// 解析JSON请求体
app.use(express.json());
// 托管静态网页(网页文件需放在当前目录的public文件夹下)
app.use(express.static('public'));

// 存储终端输出的变量,初始化为空字符串
let terminalOutput = '';

// 接收Bot发送的消息
app.post('/terminal-output', (req, res) => {
  if (req.body.output) {
    // 追加新消息,换行分隔
    terminalOutput += `${req.body.output}\n`;
  }
  res.sendStatus(200);
});

// 返回当前所有输出
app.get('/terminal-output', (req, res) => {
  res.send(terminalOutput);
});

// 启动服务器
app.listen(3000, () => {
  console.log('服务器运行在 http://localhost:3000');
});

3. 网页代码(保存到服务器的public文件夹下,命名为index.html)

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Discord机器人实时输出</title>
  <style>
    #terminal-output {
      font-family: monospace;
      background-color: #000;
      color: #fff;
      padding: 20px;
      height: 400px;
      overflow-y: auto;
      white-space: pre-wrap;
    }
  </style>
</head>
<body>
  <div id="terminal-output"></div>

  <script>
    const outputDiv = document.getElementById('terminal-output');
    let lastOutput = '';

    async function fetchTerminalOutput() {
      try {
        const response = await fetch('/terminal-output');
        if (!response.ok) throw new Error('请求失败');
        const currentOutput = await response.text();
        // 仅当内容变化时更新DOM,避免冗余操作
        if (currentOutput !== lastOutput) {
          outputDiv.textContent = currentOutput;
          // 自动滚动到底部
          outputDiv.scrollTop = outputDiv.scrollHeight;
          lastOutput = currentOutput;
        }
      } catch (error) {
        console.error('获取输出失败:', error.message);
      }
    }

    // 每2秒轮询一次(可根据需求调整)
    setInterval(fetchTerminalOutput, 2000);
    // 页面加载时立即获取一次
    fetchTerminalOutput();
  </script>
</body>
</html>

额外配置说明

  1. Discord开发者后台设置:

    • 进入Discord开发者门户,找到你的Bot应用。
    • 切换到Bot标签页,在Privileged Gateway Intents下开启Message Content Intent。
    • 确保Bot已邀请到目标服务器,且具备发送消息、读取消息的权限。
  2. 运行步骤:

    • 启动Express服务器:node server.js
    • 启动Discord机器人:node bot.js
    • 访问http://localhost:3000即可查看实时输出

内容的提问来源于stack exchange,提问作者Shaheer Ahmed Khan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 01:50:20