我想制造一个不和谐的机器人。从console.log(client.guilds)运行ping.js时,它返回undefined。但是,当我从console.log(client.guilds)运行index.js时,它会返回一个数组。我的文件结构如下所示:
文件内容ping.js:
const { SlashCommandBuilder } = require('discord.js');
module.exports = {
data: new SlashCommandBuilder()
.setName('ping')
.setDescription('Replies with Pong!'),
async execute(interaction) {
client = require('./../index.js');
console.log(client.guilds);
}
};发布于 2022-08-17 14:34:10
我没有破坏导入的对象的结构。
const { client } = require('./../index.js');谢谢Zsolt Meszaros
发布于 2022-08-17 13:05:58
可能在导出状态中没有缓存公会(您应该考虑在触发就绪事件之后导出您的客户端,或者获取所有公会)。
client.guilds.fetch() 获取所有公会并缓存它们,您可以将代码片段合并到代码中,如下所示:
const { SlashCommandBuilder } = require('discord.js'),
client = require('./../index.js');
module.exports = {
data: new SlashCommandBuilder()
.setName('ping')
.setDescription('Replies with Pong!'),
async execute(interaction) {
client.guilds.fetch().then( ( guilds ) => console.log(guilds))
}
};斜杠命令处理程序的另一种友好方法通常是将client声明为execute函数中的一个正式参数,并调用链接到index.js文件的interactionCreate中的函数,通过直接将其绑定到client来进一步处理所有事件,而不是像这样导出它:
index.js
// file being the individual file ( you can loop through your events folder
const event = require(`./events_dir/${file}`),
eventName = file.split(".")[0];
client.on(eventName, event.bind(null, client));interactionCreate.js
// command representing the individual command from your commands collection
module.exports = (client, interaction) => {
command.execute(client, interaction);
}ping.js
execute(client, interaction) {
console.log(client.guilds);
}https://stackoverflow.com/questions/73388521
复制相似问题