Discord.js bot 无法向特定频道发送消息

时间:2021-03-12 05:00:16

标签: javascript node.js discord.js

我正在尝试让我的机器人向 Discord 上的特定频道发送消息。但是,当我使用该命令时,它会导致错误:TypeError: Cannot read property 'cache' of undefined .

这是我的代码:

module.exports = {
    name: 'send',
    description: 'sends a message testing',
    execute(client) {
        const channel01 = client.channels.cache.find(channel => channel.id === "768667222527705148");
        channel01.send('Hi');
    },
};

在我的 index.js 文件中,我在开头有以下内容,所以我认为 .channels 前面的客户端用法不是问题。

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();

这是我的 Index.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);
}

const cooldowns = new Discord.Collection();

client.once('ready', () => {
    console.log('Ready!');
    client.user.setActivity("KevinYT", {
        type: "WATCHING",
        url: "https://www.youtube.com/channel/UCUr50quaTjBKWL1fLuWRvCg?view_as=subscriber"
      });
});

client.on('message', message => {

    if (!message.content.startsWith(prefix) || message.author.bot) return;

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

    const command = client.commands.get(commandName)
        || client.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName));

    if (!command) return;

    if (command.guildOnly && message.channel.type === 'dm') {
        return message.reply('I can\'t execute that command inside DMs!');
    }

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

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

        return message.channel.send(reply);
    }

    if (!cooldowns.has(command.name)) {
        cooldowns.set(command.name, new Discord.Collection());
    }

    const now = Date.now();
    const timestamps = cooldowns.get(command.name);
    const cooldownAmount = (command.cooldown || 3) * 1000;

    if (timestamps.has(message.author.id)) {
        const expirationTime = timestamps.get(message.author.id) + cooldownAmount;

        if (now < expirationTime) {
            const timeLeft = (expirationTime - now) / 1000;
            return message.reply(`please wait ${timeLeft.toFixed(1)} more second(s) before reusing the \`${command.name}\` command.`);
        }
    }

    timestamps.set(message.author.id, now);
    setTimeout(() => timestamps.delete(message.author.id), cooldownAmount);

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

client.login(token);

我错过了什么?谢谢!

1 个答案:

答案 0 :(得分:0)

command.execute(message, args)

您将 execute 函数 message(一个 Message 对象)作为第一个参数传递,但您试图将它用作 Client 对象。代码失败,因为 message.channelsundefined(混淆是由 execute 函数中使用的参数名称引起的)。

您可以使用 message.client 访问 Client 对象。

module.exports = {
  // ...
  execute (message) {
    const channel01 = message.client.channels.cache.find(
      (channel) => channel.id === '768667222527705148'
    )
    // ...
  },
}