javascript - client.guilds.cache.size 是否损坏?

标签 javascript discord.js

我正在尝试让我的不和谐机器人显示它所在的服务器数量作为其状态,但是当我执行 client.guilds.cache.size 时它只显示 0。我的 friend 也发生了这种情况。

这是我的代码,如果有任何用处......

const fs = require('fs');
const Discord = require('discord.js');
const { prefix, token } = require('./myconfig10.json');
const client = new Discord.Client();
const cheerio = require('cheerio');
const request = require('request');
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
const embedAuthor = ('This bot was made by <my discord name>')
const servers = client.guilds.cache.size


//Telling the bot where to look for the commands
for (const file of commandFiles) {
    const command = require(`./commands/${file}`);
    client.commands.set(command.name, command);
}

//Once the bot is up and running, display 'Ready' in the console
client.once('ready', () => {
    console.log('Ready!');
    client.user.setActivity(`on ${servers}`);
});

//Seeing if the message starts with the prefix
client.on('message', message => {
    if (!message.content.startsWith(prefix) || message.author.bot) return;

//Telling the bot what arguments are
    const args = message.content.slice(prefix.length).trim().split(/ +/)
    const commandName = args.shift().toLowerCase();

//Checking to see if the command you sent is one of the commands in the commands folder 
    if (!client.commands.has(commandName)) return;
    console.log(`Collected 1 Item, ${message}`)

    const command = client.commands.get(commandName);

//Try to execute the command.
    try {
        command.execute(message, args);
    
//If there's an error, don't crash the bot. 
    } catch (error) {
        console.error(error);
        
//Sends a message on discord telling you there was an error
        message.reply('there was an error trying to execute that command!');

它说:

Its says 'Playing on 0' on my bot's status

最佳答案

问题是您试图在客户端准备好之前获取guilds集合。您需要将获取 client.guilds.cache.size 的代码移至 ready 事件处理程序中。

client.once('ready', () => {
    console.log('Ready!');
    client.user.setActivity(`on ${client.guilds.cache.size}`);
});

相关资源:
Why does client.guilds.cache.size only say "0" in my playing status even if it's in 2 servers?

关于javascript - client.guilds.cache.size 是否损坏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65221973/

相关文章:

javascript - jQuery 选择器排除事件中的其他元素

javascript - 如何在 Drupal 8 主题中添加 javascript 库?

javascript - 创建 React App + Express.js + Passport.js 登录问题

javascript - 鼠标悬停更改图像

javascript - 使用 Javascript 向用户发送 HTTP 附件(打开浏览器的“另存为...”对话框)

javascript - Node Canvas 对未知字符使用后备字体

javascript - Discord.js (v13) SlashCommandBuilder addIntegerOption 设置范围

embed - 使用命令更改 channel 名称并发送嵌入

javascript - 检查用户是否具有任何列出的所需权限

javascript - 根据使用的邀请码为新成员分配角色