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

Discord机器人使用discord-xp排行榜报错Cannot read property 'cache' of undefined

错误根因

报错TypeError: Cannot read property 'cache' of undefined指向client.users.cache字段,本质是client.users本身为未定义状态,触发原因分为两类:

  • 调用computeLeaderboard方法时参数顺序错误,第一个入参不是已完成初始化的Discord.js Client实例
  • 使用Discord.js v13及以上版本时,未开启GuildMembers等必要网关意图,导致客户端用户缓存未正常挂载

可行解决方案

1. 修正调用参数

检查你项目根目录index.js第61行的调用代码,确保参数顺序符合要求,第一个参数必须是你初始化的Discord客户端实例,正确调用示例:

// 先拉取原始排行榜数据
const rawLeaderboard = await DiscordXp.fetchLeaderboard(interaction.guild.id, 10);
// 按顺序传入client实例、原始排行榜数据
const computedLeaderboard = await DiscordXp.computeLeaderboard(client, rawLeaderboard, false);

2. 开启必要网关意图(适配Discord.js v13+)

初始化客户端时开启Guilds、GuildMembers两个核心意图,保证用户缓存可以正常加载:

const { Client, GatewayIntentBits } = require('discord.js');
const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMembers,
    // 其他你需要开启的意图
  ]
});

3. 切换拉取模式规避缓存依赖

调用computeLeaderboard时将第三个参数设为true,直接走官方接口拉取用户数据,不需要依赖本地缓存,兼容性更高:

const computedLeaderboard = await DiscordXp.computeLeaderboard(client, rawLeaderboard, true);

4. 源码兜底优化(可选)

如果需要修改discord-xp源码兼容异常场景,可以将computeLeaderboard方法else分支的代码替换为可选链+空值合并的写法,避免空值报错:

username: client?.users?.cache?.get(key.userID)?.username ?? "Unknown",
discriminator: client?.users?.cache?.get(key.userID)?.discriminator ?? "0000"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 07:00:03