【问题标题】:Cannot read property 'fetch' of undefined - any assistance appreciated无法读取未定义的属性“获取” - 感谢任何帮助
【发布时间】:2021-09-10 15:39:19
【问题描述】:

所以基本上,我在尝试启动我的机器人时遇到了这个错误。它是使用 Discord.js 构建的

/home/container/events/serverStats.js:5
const totalUsers = client.channels.fetch('XX');
                                   ^

TypeError: Cannot read property 'fetch' of undefined
    at Object.<anonymous> (/home/container/events/serverStats.js:5:36)
    at Module._compile (node:internal/modules/cjs/loader:1092:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1121:10)
    at Module.load (node:internal/modules/cjs/loader:972:32)
    at Function.Module._load (node:internal/modules/cjs/loader:813:14)
    at Module.require (node:internal/modules/cjs/loader:996:19)
    at require (node:internal/modules/cjs/helpers:92:18)
    at Object.<anonymous> (/home/container/index.js:83:19)
    at Module._compile (node:internal/modules/cjs/loader:1092:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1121:10)

代码文件本身如下所示:

const Discord = require('discord.js');
const config = require('../settings/config.js');
const client = require('../index.js');
const Guild_ID = require('../settings/configuration').BOT_SETTINGS;
const totalUsers = client.channels.fetch('858369874110971914');
const onlineUsers = client.channels.fetch('858370257797513236');
const codeMonkeys = client.channels.fetch('858370529902985227');

client.guilds.fetch('XX')
  .then(guild => console.log(guild.name))
  .catch(console.error);

这是我的索引文件的样子:

require('./structures/Guild')
const Discord = require('discord.js');
const client = new Discord.Client();
const { Collection, Client, MessageEmbed } = require("discord.js");
const { Manager } = require('@lavacord/discord.js')
const { readdirSync } = require("fs");
const { BOT_TOKEN, EMBED_COLOR, MUTE_ROLE, YT_API_KEY, COMMAND_PREFIX } = require("./settings/configuration").BOT_SETTINGS;
const db = require('quick.db')
const path = require("path");
const logSymbols = require('log-symbols');
const Enmap = require('enmap');
const Tickets = new Enmap({ name: 'tickets' });
const i18n = require('i18n');
client.tickets = Tickets;
if (!COMMAND_PREFIX) throw new Error('Please provide a prefix in the configuration')
if (!BOT_TOKEN) throw new Error('Please provide a valid bot token to start the bot\nObtain one from here https://discord.com/developers/applications')
if (!YT_API_KEY) throw new Error('Please provide a Youtube API key in the configuration.\nGet one here https://developers.google.com/youtube/v3/getting-started')
if (!EMBED_COLOR) throw new Error('Please provide an embed hex color in the configuration. E.g. RED or #fl92jd')

console.log(logSymbols.success, 'Finished successfully!');

client.StickyMessages = new db.table(`sticky`)
const StickyMessages = new db.table(`sticky`)

client.db = require('quick.db')
client.embed = class Embed extends MessageEmbed { color = EMBED_COLOR }


client.on('ready', () => {
    console.log(`Logged in as ${client.user.tag}!`);
    client.user.setActivity(`Watching you!`, {
        type: "WATCHING"
    });

});
i18n.configure({
  locales: ["en", "ko", "fr", "pt_br", "zh_cn", "zh_tw"],
  directory: path.join(__dirname, "locales"),
  defaultLocale: "en",
  objectNotation: true,
  register: global,
  logErrorFn: function (msg) {
    console.log("error", msg);
  },

  missingKeyFn: function (locale, value) {
    return value;
  },

  mustacheConfig: {
    tags: ["{{", "}}"],
    disable: false
  }
});

client.snipes = new Collection()
client.commands = new Collection();
client.color = EMBED_COLOR;
client.muteRole = MUTE_ROLE;
client.afk = new Collection()
client.spam = new Collection()
    //client.handle = require("./functions/handle");
    //client.play = require("./functions/play");
client.queue = new Collection()
client.categories = new Collection()

client.db = {
    ...require('quick.db'),
    ensure: (key, def) => {
        if (db.get(key)) return db.get(key)
        db.set(key, def)
        return db.get(key, def)
    }
}
client.manager = new Manager(client, [{ id: 'main', host: 'localhost', port: 2333, password: 'brandon2511' }])
client.manager.on('ready', node => console.log(`Node ${node.id} is ready!`))
    .on('disconnect', (ws, node) => console.log(`Node ${node.id} disconnected.`))
    .on('reconnecting', node => console.log(`Node ${node.id} tries to reconnect.`))
    .on('error', (error, node) => console.log(`Node ${node.id} got an error: ${error.message}`))

const eventFiles = readdirSync("./events").filter(f => f.endsWith(".js"));
for (const file of eventFiles) {
    const event = require(`./events/${file}`);
    if (event.name) {
        client.on(event.name, (...args) => event.execute(client, ...args));
        console.log(`[√] Event ${file} has been successfully loaded!`);
    }
}

const categories = ['fun', 'info', 'moderation', 'system', 'tickets', 'basic', 'music'];
categories.forEach(async category => {
    const commandFiles = readdirSync(`./commands/${category}`).filter(f => f.endsWith(".js"));
    if (category !== 'owner') client.categories.set(category, commandFiles.map(s => s.split('.')[0]))
    for (const file of commandFiles) {
        try {
            const command = require(`./commands/${category}/${file}`);
            if (command.config) {
                client.commands.set(file.split('.')[0], { name: file.split('.')[0], ...command });
                console.log(`[√] Command ${file.split('.')[0]} has been successfully loaded!`);
            } else throw new Error('Command missing config')
        } catch (e) {
            console.log(`[❌] Command ${file} failed to load: ${e.message}`)
        }
    }
});

client.login(BOT_TOKEN).catch(() =>
    console.log(
        `[❌] Error while trying bot to log in.
  [⚠️ POSSIBLE FIX] You provided an invalid token of the bot`
    )
);

这是我的配置文件的第一部分:

module.exports = {
    BOT_SETTINGS: {
        BOT_TOKEN: 'XX',
        YT_API_KEY: 'XX',
        COMMAND_PREFIX: '?',
        EMBED_COLOR: 'BLUE',
        MUTE_ROLE: '841079005892968458',
        BANNED_WORDS: ['retard', 'nigger'],
        BYPASS_ROLES: ['802711739006582846'],
        BANNED_LINKS: ['www.', '.com', '.net', '.gov', '.co', '.uk', '.gg', '.live'],
        BYPASS_LINKS_ROLES: ["802711739006582846"],
        Member_Count_Channel: '809569469030596648',
        Guild_ID: '802700035544317972',
        Kick_On_Warnings: true,
        Warnings_Until_Kick: '5',
        Time_Muted: '1m',
        LOCALE: 'en',
        Roles_On_Join: ['803388467588628490']
    },

有什么想法吗?我已经尝试了所有明显的修改,这让我坚持了 72 小时!我真的很想知道问题是什么以及它们的修复方法

【问题讨论】:

标签: javascript node.js discord.js


【解决方案1】:

错误是说client.channels 未定义。

您应该做的第一件事是检查client 是什么,也许通过记录它。从您的代码中,我可以看到您正在从 index.js 中检索 client。但是在 index.js 中,你没有导出任何东西,所以它默认为一个空白对象。

您需要在 index.js 文件中的某处添加它(可能在末尾)。

module.exports = client;

【讨论】:

  • 我已将它添加到我的索引文件中,但它仍未被接受,同样的错误?
  • 然后在你的 serverStats.js 中记录客户端是什么。
  • 所以这个? js module.exports = new Discord.Client;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-05
  • 2020-02-14
  • 1970-01-01
  • 1970-01-01
  • 2020-12-05
  • 2021-04-14
相关资源
最近更新 更多