You need to enable JavaScript to run this app. Discord.js开发中info指令使用client.guilds.cache.size显示0的原因
优惠活动
大模型
产品
解决方案
定价
更多

Discord.js开发中info指令使用client.guilds.cache.size显示0的原因

Discord Bot 服务器计数恒为0问题修正

问题表现

开发Discord Bot的info指令时,调用client.guilds.cache.size获取机器人加入的服务器总数,指令返回的数值始终为0,和Bot实际加入的服务器数量不匹配。
问题对应的原始代码片段:

const { DiscordAPIError, MessageEmbed } = require("discord.js");
const config = require("../config.json");
const Discord = require('discord.js');
const client = new Discord.Client();
const prefix = config.prefix;

module.exports = {
    name: 'info',
    description: "info",
    execute(message, args, Discord) {
        const newEmbed = new MessageEmbed()
        .setColor('RANDOM')
        .setFooter('Info for Laughing Horse 🤖')
        .addFields(
            {name: 'Bot tag', value: '`Laughing Horse#6722`'},
            {name: 'Version', value: '`1.0.4`'},
            {name: 'Prefix', value: prefix},
            {name: 'Bot Dev', value: '`Skep#2721`'},
            {name: 'server count', value: `the bot is currently in ${client.guilds.cache.size} servers`}
        )
        message.channel.send(newEmbed);
    }
}

核心原因

  • 代码在info指令模块内单独创建了一个全新的Discord.Client实例,这个实例没有执行Bot登录流程,也没有和Discord网关建立连接,本身不携带任何服务器缓存数据
  • 这个独立的空Client和主程序里真正运行Bot、持续同步服务器列表的Client完全独立,二者没有任何数据关联,因此读取这个空实例的guilds.cache.size,结果永远是0
  • 旧代码在execute方法参数中传入Discord构造器的写法,在discord.js v14+版本已经完全废弃,无法获取真实的Bot运行状态

修正步骤

  • 删除指令文件内多余的Discord模块引入、Client初始化逻辑,不要在子模块内重复创建独立的Client实例
  • 直接使用消息上下文自带的message.client属性获取和当前Bot关联的真实Client,不需要额外传参就能拿到同步后的服务器缓存数据
  • 修正后的参考代码:
const { MessageEmbed } = require("discord.js");
const config = require("../config.json");
const prefix = config.prefix;

module.exports = {
    name: 'info',
    description: "info",
    execute(message, args) {
        const guildCount = message.client.guilds.cache.size;
        const newEmbed = new MessageEmbed()
        .setColor('RANDOM')
        .setFooter('Info for Laughing Horse 🤖')
        .addFields(
            {name: 'Bot tag', value: '`Laughing Horse#6722`'},
            {name: 'Version', value: '`1.0.4`'},
            {name: 'Prefix', value: prefix},
            {name: 'Bot Dev', value: '`Skep#2721`'},
            {name: 'server count', value: `the bot is currently in ${guildCount} servers`}
        )
        message.channel.send(newEmbed);
    }
}
  • 若修正后数值仍存在偏差,可进一步检查Bot在Discord开发者门户是否开启了guilds意图,确保登录时能正常拉取全量服务器列表同步到本地缓存。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.28 15:36:10