提问者:小点点

如何修复此错误:“类型错误:无法读取 Discordjs 中未定义的属性(读取'toLowerCase')”?


直到今天,此错误才成为问题。每次我运行我的 discordjs 机器人时,它都会给我一个 TypeError 说“无法读取未定义的属性(读取'toLowerCase')”

这是我的代码

const { readdirSync } = require('fs');
const { Collection } = require('discord.js');



client.commands = new Collection();

const events = readdirSync('./events/').filter(file => file.endsWith('.js'));

console.log(`Loading events...`);

for (const file of events) {
    const event = require(`../events/${file}`);
    console.log(`-> Loaded event ${file.split('.')[0]}`);
    client.on(file.split('.')[0], event.bind(null, client));
    delete require.cache[require.resolve(`../events/${file}`)];
};

console.log(`Loading commands...`);

readdirSync('./commands/').forEach(dirs => {
    const commands = readdirSync(`./commands/${dirs}`).filter(files => files.endsWith('.js'));

    for (const file of commands) {
        const command = require(`../commands/${dirs}/${file}`);
        console.log(`-> Loaded command ${command.name.toLowerCase()}`);
        client.commands.set(command.name.toLowerCase(), command);
        delete require.cache[require.resolve(`../commands/${dirs}/${file}`)];
    };
});

当我运行机器人时,输出是这样的

Loading events...
-> Loaded event interactionCreate
-> Loaded event messageCreate
-> Loaded event ready
Loading commands...
TypeError: Cannot read properties of undefined (reading 'toLowerCase')
    at /home/runner/Saeki-Miyako-Bot/src/loader.js:26:55
    at Array.forEach (<anonymous>)
    at Object.<anonymous> (/home/runner/Saeki-Miyako-Bot/src/loader.js:21:28)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (/home/runner/Saeki-Miyako-Bot/main.js:43:1)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! music-bot@12.22.6 start: `node main.js`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the music-bot@12.22.6 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/runner/.npm/_logs/2021-10-26T03_01_19_546Z-debug.log
exit status 1

共1个答案

匿名用户

这意味着您的命令(导入文件)并非都具有相同的结构(带有属性“name”)。

如果没有名称的命令不重要,则可以筛选出它们:

for (const file of commands) {
  const command = require(`../commands/${dirs}/${file}`);
  if (!command || !command.name) {
    console.warn(`Name is missing in 'commands/${dirs}/${file}'`)
    continue;
  }

  console.log(`-> Loaded command ${command.name.toLowerCase()}`);
  client.commands.set(command.name.toLowerCase(), command);
  delete require.cache[require.resolve(`../commands/${dirs}/${file}`)];
};

由于我无法访问您的文件系统,因此我看不到文件的内容。但我假设某些文件(命令)中缺少该名称。