module.export 并获取用户信息

module.export and getting user information

我正在尝试通过 module.export 在命令文件中显示 client.user.avatarURL 使用:

...
icon_url: client.user.avatarURL;
...

但是当我通过机器人调用命令时,我在控制台中出现了这个错误:

TypeError: Cannot read property 'avatarURL' undefined

我试过在 const 上获取客户端的值并将其传递给命令处理程序,但也没有解决它。如果您删除该行,一切正常,所以我想这是传递客户信息的错误方式。

main.js

const fs = require('fs');
const Discord = require('discord.js');
const { prefix, token } = require('./config.json');

const client = new Discord.Client();
client.commands = new Discord.Collection();


const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));

for (const file of commandFiles) {
    const command = require(`./commands/${file}`);
    client.commands.set(command.name, command);
}

client.once('ready', () => {
    console.log('Online!');
});

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

    const args = message.content.slice(prefix.length).split(/ +/);
    const commandName = args.shift().toLowerCase();

    if (!client.commands.has(commandName)) return;
    const command = client.commands.get(commandName);

    if (command.args && !args.length) {
        let reply = `You didn't provide enough arguments, ${message.author}!`;

        if (command.usage) {
            reply += `\nThe proper usage would be: \n\`${prefix}${command.name} ${command.usage}\``;
        }

        return message.channel.send(reply);
    }


    try {
        command.execute(message, args, client);
    }
    catch (error) {
        console.error(error);
        message.reply('there was an error trying to execute that command!');
    }
});

client.login(token);

和命令文件:

module.exports = {
    name: 'help',
    description: 'Help file',
    execute(message, client) {
        message.channel.send({ embed: {
            color: 0xf7da66,
            author: {
                name: 'Bot',
                icon_url: client.user.avatarURL,
            },
            title: 'commands guide',
            description: 'This is an discord bot.',
            fields: [{
                name: 'Command',
                value: 'Type: example.',
            },
            ],
            timestamp: new Date(),
            footer: {
                icon_url: client.user.avatarURL,
                text: '© Bot',
            } } });
    },
};

你正在做:command.execute(message, args, client); 但随后 execute(message, client) { 这意味着在你的命令文件中 client 实际上不是数组 args.

您需要做:execute(message, args, client) {

您需要改用 module.exports = (client, message, args) => {