首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Client.guilds未定义为discord.js

问Client.guilds未定义为discord.js
EN

Stack Overflow用户
提问于 2022-08-17 12:31:23
回答 2查看 46关注 0票数 0

我想制造一个不和谐的机器人。从console.log(client.guilds)运行ping.js时,它返回undefined。但是,当我从console.log(client.guilds)运行index.js时,它会返回一个数组。我的文件结构如下所示:

  • discord-bot/index.js
  • discord-bot/commands/ping.js

文件内容ping.js:

代码语言:javascript
复制
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);
        
        }
};
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-08-17 14:34:10

我没有破坏导入的对象的结构。

代码语言:javascript
复制
const { client } = require('./../index.js');

谢谢Zsolt Meszaros

票数 0
EN

Stack Overflow用户

发布于 2022-08-17 13:05:58

可能在导出状态中没有缓存公会(您应该考虑在触发就绪事件之后导出您的客户端,或者获取所有公会)。

代码语言:javascript
复制
client.guilds.fetch() 

获取所有公会并缓存它们,您可以将代码片段合并到代码中,如下所示:

代码语言:javascript
复制
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

代码语言:javascript
复制
// 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

代码语言:javascript
复制
// command representing the individual command from your commands collection
module.exports = (client, interaction) => {
command.execute(client, interaction);
}

ping.js

代码语言:javascript
复制
execute(client, interaction) {
console.log(client.guilds);
}
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73388521

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档