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

discord.js跨文件使用client对象导致部署命令报错

问题分析与解决

核心原因

你遇到的报错是循环依赖导致的模块加载顺序混乱:index.js在加载命令文件(比如ping.js)时,ping.js又反向require了index.js,此时index.js还未完成全部代码执行,导致命令模块的data属性未被正确读取,最终触发Cannot read properties of undefined (reading 'name')错误。

解决方案

方案1:将client作为参数传入命令执行函数

不需要在命令文件中引入index.js,而是在执行命令时把client传递给execute函数:

  1. 修改ping.js的execute函数,增加client参数:
const { SlashCommandBuilder } = require('discord.js');

module.exports = {
  data: new SlashCommandBuilder()
    .setName('ping')
    .setDescription('返回机器人延迟'),
  async execute(interaction, client) {
    await interaction.reply(`Pong! ${client.ws.ping}ms`);
  }
};
  1. 在index.js的interactionCreate事件中,调用execute时传入client:
client.on('interactionCreate', async interaction => {
  if (!interaction.isChatInputCommand()) return;

  const command = client.commands.get(interaction.commandName);
  if (!command) return;

  try {
    await command.execute(interaction, client); // 传入client
  } catch (error) {
    console.error(error);
    await interaction.reply({ content: '执行命令时出错!', ephemeral: true });
  }
});

方案2:拆分client到独立模块

创建单独的client模块,让index.js和命令文件都从这个模块引入,彻底避免循环依赖:

  1. 创建src/utils/client.js文件,专门初始化并导出client:
const { Client, GatewayIntentBits } = require('discord.js');
const client = new Client({ intents: [GatewayIntentBits.Guilds] });

module.exports = client;
  1. 在index.js中引入这个client:
const client = require('./utils/client');
// 后续的登录、命令加载等逻辑保持不变
  1. 在ping.js中直接引入独立的client模块:
const { SlashCommandBuilder } = require('discord.js');
const client = require('../utils/client');

module.exports = {
  data: new SlashCommandBuilder()
    .setName('ping')
    .setDescription('返回机器人延迟'),
  async execute(interaction) {
    await interaction.reply(`Pong! ${client.ws.ping}ms`);
  }
};

验证

修改完成后,重新部署命令即可正常执行,同时ping命令也能正确获取client的延迟数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 14:15:29