You need to enable JavaScript to run this app. 如何使用JS获取指定Discord服务器在线人数并在网站展示?
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JS获取指定Discord服务器在线人数并在网站展示?

获取Discord服务器在线人数并展示在网站上的正确方法

你的代码出现404的原因

你使用的API端点https://discord.com/api/memberCount/{ID}/embed.json是无效的,Discord官方从未提供过这个接口,因此请求会返回404错误。

解决方案

以下两种可行方式,可根据你的服务器类型选择:

方法一:使用Discord服务器Widget API(无需认证,适合公开服务器)

这个方法需要先在Discord服务器中开启Widget功能:

  • 打开Discord服务器设置,进入「Widget」页面
  • 开启「服务器Widget」开关,复制你的服务器ID(Guild ID)
  • 确保服务器是公开状态(私有服务器无法通过该API获取数据)

修改后的代码示例:

// 替换为你的Discord服务器ID
const guildId = "123456789012345678"; 
// 定义文本变量,原代码中未声明
const pluralText = "位用户在线";
const singularText = "位用户在线";

$.ajax({
  url: `https://discord.com/api/guilds/${guildId}/widget.json`,
  dataType: "json",
  success: function(data) {
    const onlineCount = data.presence_count;
    updateDiscordStatus(onlineCount);
  },
  error: function() {
    // 请求失败时的降级处理,比如显示0或提示文字
    updateDiscordStatus(0);
  },
  timeout: 30000 // 超时时间设为30秒更合理
});

function updateDiscordStatus(presenceCount) {
  const statusDiv = $(".discord-status");
  statusDiv.empty();
  
  const displayText = presenceCount !== 1 ? pluralText : singularText;
  statusDiv.html(`<span class='status-number'>${presenceCount}</span> ${displayText}`);
}

该API返回的关键字段:

  • presence_count: 当前在线的成员数
  • member_count: 服务器总成员数

方法二:使用Discord官方REST API(需要Bot认证,适合私有服务器)

如果你的服务器是私有,或需要更详细的成员数据,需创建Discord Bot并使用官方API:

  1. 在Discord开发者平台创建Bot,获取Bot Token
  2. 将Bot邀请到目标服务器,确保Bot拥有View Guild Insights或Server Members Intent权限
  3. 由于前端直接请求会遇到CORS限制,建议通过后端代理请求API,再由前端请求后端接口获取数据

后端请求示例(Node.js):

const fetch = require('node-fetch');

const guildId = "你的服务器ID";
const botToken = "你的Bot Token";

async function getOnlineCount() {
  const response = await fetch(`https://discord.com/api/v10/guilds/${guildId}?with_counts=true`, {
    headers: {
      "Authorization": `Bot ${botToken}`
    }
  });
  const data = await response.json();
  return data.approximate_presence_count; // 在线人数
}

原代码的其他问题修正

  • users_online和user_online变量未声明,需提前定义文本内容
  • 判断逻辑(presence_count > 1) || (presence_count < 1)可简化为presence_count !== 1
  • 超时时间设置为300000(5分钟)过长,建议缩短至30秒内

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 19:01:09