我有一个命令处理程序,它是模块,并像这样构造。
module.exports ={
name: "test",
execute(message, args) {
var yes = client.channels.cache.get('818107649912209438')
yes.send('some message')
}
每当我尝试向特定频道发送消息时,机器人都会返回一个错误:
var yes = client.channels.cache.get("818107649912209438");
^
TypeError: Cannot read property 'channels' of undefined
我一直在努力解决这个问题,但没有运气。如果有人知道为什么它不起作用并愿意提供帮助,我将不胜感激。
答案 0 :(得分:2)
您的错误 'of undefined'
意味着您正在通过某些东西访问 channel 属性,但某些东西未定义。在此命令处理程序中,您没有定义 client
。您必须将 client
对象作为您在主文件中定义的参数(如 execute(message,args,client)
)传递,然后访问客户端的属性或方法。
答案 1 :(得分:0)
你的问题不是很清楚,所以我给你一个例子来说明如何处理,稍后我会展示代码和解释。
格式:
// I used message as msg to shorten my code.
const all_requires = require("../settings/settings"); // Exported all requires
const { config, Discord, client } = all_requires; // Imported what I need
module.exports = (client, msg) => {
if(msg.author.bot || !msg.content.startsWith(config.prefix)) return;
const args = msg.content.split(" ").slice(1);
const command = msg.content.split(' ')[0].slice(config.prefix.length);
const cmd = client.commands.get(command); //enmap handler
console.log(cmd);
if(!cmd) return;
cmd.run(msg, args);
}
module.exports.run = (msg) => {
msg.channel.send("Pong!");
}
{
"token": "TOKEN-HERE",
"prefix": "+"
}
const Discord = require("discord.js");
const fs = require("fs");
const enmap = require("enmap");
const config = require("../config/config.json");
const client = new Discord.Client();
const all_requires = { Discord, fs, enmap, config, client }
module.exports = all_requires;
index.js
const all_requires = require("./settings/settings");
const { Discord, fs, enmap, config, client } = all_requires;
client.commands = new enmap;
client.once("ready", () => {
console.log(`${client.user.tag} is Connected.`);
})
fs.readdir("./events/", (err, files) => {
if(err) return console.error(err);
files.forEach(file => {
const event = require(`./events/${file}`);
let eventName = file.split(".")[0];
client.on(eventName, event.bind(null, client));
});
console.log(`${files.length} Events Loaded.`)
});
fs.readdir("./commands/", (err, files) => {
if(err) return console.error(err);
files.forEach(file => {
let props = require(`./commands/${file}`);
let commandName = file.split(".")[0];
client.commands.set(commandName, props);
});
console.log(`Loaded ${files.length} Commands.`);
});
process.on('unhandledRejection', err => console.log(err));
client.login(config.token);
作为处理程序,您需要向我展示整个代码以了解您在做什么来处理命令,您可以使用 enmap
link 就像在基本代码示例中一样,或者使用discord.js
link Handlers 来执行命令,看 message.js
Line:8 client.commands.get()
这里我们定义了 enmap handler,在 Line:13 对于 cmd.run()
我们只使用 module.exports.run
运行命令,我们在 index.js
Line:3 中定义了命令处理程序,我们设置了fs
for 循环内的 Line:24 中的命令。
-享受编码。