Discord.js中ping.js调用client.guilds返回undefined问题求助
解决Discord机器人命令文件中client.guilds返回undefined的问题
问题原因
你在ping.js里通过require('./../index.js')获取的client是undefined,核心原因是**index.js没有将创建好的Discord Client对象导出**。
修复步骤
1. 修改index.js,导出Client对象
在index.js中,创建完client实例后,添加导出语句:
// index.js示例代码 const { Client, GatewayIntentBits } = require('discord.js'); const client = new Client({ intents: [GatewayIntentBits.Guilds] }); // 你的其他初始化代码(比如事件监听、命令加载等) // 在文件末尾导出client module.exports = client;
2. 修改ping.js,正确导入client
将ping.js里的client导入移到文件顶部,避免在execute函数内动态加载:
const { SlashCommandBuilder } = require('discord.js'); // 直接导入index.js导出的client const client = require('./../index.js'); module.exports = { data: new SlashCommandBuilder() .setName('ping') .setDescription('Replies with Pong!'), async execute(interaction) { console.log(client.guilds); // 必须回复交互,否则Discord会判定命令超时 await interaction.reply('Pong!'); } };
额外注意事项
- 确保
index.js中已经调用了client.login('你的机器人令牌'),且客户端完成登录后,client.guilds才会包含实际的服务器数据。 - 不要在
execute函数内部重复require文件,这会导致模块重复加载,可能引发意外问题。
内容的提问来源于stack exchange,提问作者user19784958
相关产品推荐
相关产品推荐

