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

如何在HTML页面中自动展示Discord Bot的服务器数量与用户总数量

实现Discord Bot统计数据自动更新的方法

整体实现逻辑分为3步:先从Bot端获取真实统计数据,再搭建接口供前端调用,最后前端拉取数据更新页面内容。

1. 从Bot端获取真实统计数据

以常用的discord.js库为例:

  • 服务器总数可以直接取客户端的client.guilds.cache.size属性
  • 总用户数需要累加所有服务器的成员数量,注意需要先在Discord开发者后台的Bot设置页,开启「Privileged Gateway Intents」下的Server Members Intent权限,才能拿到完整的服务器成员列表。

2. 搭建统计数据接口

你可以直接在Bot的代码中集成轻量HTTP服务,比如用express框架暴露一个GET接口,接口返回JSON格式的统计数据,示例逻辑如下:

const express = require('express')
const app = express()
// 配置跨域,允许你的网站域名访问
app.use(require('cors')({ origin: '你的网站域名' }))

app.get('/api/stats', (req, res) => {
  // 计算总用户数
  const totalUsers = client.guilds.cache.reduce((sum, guild) => sum + guild.memberCount, 0)
  res.json({
    serverCount: client.guilds.cache.size,
    userCount: totalUsers
  })
})

app.listen(3000, () => console.log('统计接口运行在端口3000'))

如果你的Bot和网站分开部署,也可以定时把统计数据写入数据库、KV存储这类公共存储中,网站后端从存储中读取数据返回即可,注意不要把Bot Token暴露在前端代码中,所有涉及Bot权限的操作都要在服务端完成。

3. 前端拉取数据更新页面

首先修改你的HTML代码,给两个统计数值的标签加上唯一ID,方便JS选中修改:

<div class="container-fluid text-white">
    <div class="row row-cols-3 justify-content-center" style="color: var(--secondary-text-color);">
        <div class="col-auto col-md-6 col-lg-4 text-center pb-5 pt-5 number-item love_counter">
            <h1 class="love_count" style="font-size: 70px;"><strong id="serverCount">100</strong></h1>
            <h4 style="color: var(--main-color);margin-top: -6px;">Total Servers</h4>
        </div>
        <div class="col-auto col-lg-4 text-center align-self-center pb-5 pt-5 love_counter">
            <h1 class="love_count" style="font-size: 70px;"><strong id="userCount">2500</strong></h1>
            <h4 style="color: var(--main-color);margin-top: -6px;">Total Users</h4>
        </div>
    </div>
</div>

然后在页面中添加JS逻辑,页面加载时请求接口更新数据,也可以加定时器定期拉取实现准实时更新:

window.addEventListener('load', async () => {
  // 定义更新数据的函数
  const updateStats = async () => {
    try {
      const res = await fetch('你的接口地址/api/stats')
      const stats = await res.json()
      document.getElementById('serverCount').textContent = stats.serverCount
      document.getElementById('userCount').textContent = stats.userCount
    } catch (err) {
      console.error('统计数据获取失败', err)
    }
  }
  // 页面加载时立刻更新
  await updateStats()
  // 每5分钟更新一次,可根据需求调整间隔
  setInterval(updateStats, 5 * 60 * 1000)
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 11:18:03