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

如何通过服务器向JDA客户端发送信号触发Discord消息推送?

实现方案

你的思路完全可行,核心是搭建服务器到客户端的实时通信通道,触发事件时推送信号,客户端拿到信号后用本地的用户ID调用Discord接口发消息。具体分三步来做:

1. 服务器端:监听事件并推送信号

先给服务器和客户端建立实时通信链路,推荐用WebSocket(双向实时)或者SSE(单向推送,更轻量),当你要监听的特定事件触发时,服务器向连接的客户端发送触发信号。

WebSocket示例(Node.js)

用ws库实现:

const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });

// 模拟业务逻辑触发特定事件
function onServerEventTriggered() {
  // 给所有在线客户端发触发信号
  wss.clients.forEach(client => {
    if (client.readyState === WebSocket.OPEN) {
      client.send(JSON.stringify({ event: 'SEND_DISCORD_MSG' }));
    }
  });
}

// 假设某个业务流程触发了事件(比如数据库更新、用户操作)
// onServerEventTriggered();

SSE示例(Node.js)

适合只需要服务器单向推送的场景:

const http = require('http');
http.createServer((req, res) => {
  res.writeHead(200, {
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive'
  });

  // 事件触发时推送信号
  function sendTriggerSignal() {
    res.write(`data: ${JSON.stringify({ event: 'SEND_DISCORD_MSG' })}\n\n`);
  }
}).listen(8080);

2. 客户端:接收信号并调用Discord接口

客户端连接到服务器的通信通道,收到触发信号后,从本地存储(浏览器用localStorage/Cookie,桌面端用配置文件)取出用户ID,然后调用Discord的Webhook或者Bot API发送消息。

浏览器客户端示例

// 连接服务器WebSocket
const socket = new WebSocket('ws://你的服务器地址:8080');

socket.onmessage = (event) => {
  const signal = JSON.parse(event.data);
  if (signal.event === 'SEND_DISCORD_MSG') {
    // 从本地取用户ID
    const userId = localStorage.getItem('discord_user_id');
    if (!userId) {
      console.log('本地未存储用户ID');
      return;
    }
    // 调用Discord Webhook发消息
    sendMsgToDiscord(userId);
  }
};

function sendMsgToDiscord(userId) {
  // 提前在Discord频道创建Webhook,替换成你的Webhook地址
  const webhookUrl = 'https://discord.com/api/webhooks/xxx/xxx';
  fetch(webhookUrl, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      content: `服务器事件触发:关联用户ID为 ${userId}`
    })
  });
}

桌面客户端示例(Electron)

const WebSocket = require('ws');
const fs = require('fs');
const axios = require('axios');

const socket = new WebSocket('ws://你的服务器地址:8080');

socket.onmessage = (event) => {
  const signal = JSON.parse(event.data);
  if (signal.event === 'SEND_DISCORD_MSG') {
    // 从本地配置文件读取用户ID
    const config = JSON.parse(fs.readFileSync('./client-config.json', 'utf8'));
    const userId = config.discordUserId;
    sendMsgToDiscord(userId);
  }
};

function sendMsgToDiscord(userId) {
  axios.post('你的Discord Webhook地址', {
    content: `服务器特定事件触发,用户ID:${userId}`
  }).catch(err => console.log('发送消息失败:', err));
}

3. 关键细节提醒

  • 通信可靠性:WebSocket要加重连逻辑,避免客户端断连后收不到信号;
  • 用户ID安全:客户端存储用户ID时,敏感信息要加密,别明文存;
  • Discord权限:Webhook要确保有目标频道的发送消息权限,用Bot的话要正确配置Bot的权限范围;
  • 定向推送:如果不需要给所有客户端发信号,服务器可以在客户端连接时记录标识(比如用户唯一ID),事件触发时只推送给指定客户端。

内容的提问来源于stack exchange,提问作者Gary Kang

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 17:53:20