我们正在努力让我们的guildCreate.js
事件触发器为 Corion 工作。但它抛出以下错误:
3|Corion | (node:16154) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'cache' of undefined
这是我们的代码:
module.exports = async (client, guild) => {
const channel = guild.channels.cache.find(channel => channel.type === 'text' && channel.permissionsFor(guild.me).has('SEND_MESSAGES'))
console.log(`${client.name}` + `has entered` + `${guild.name}.`)
channel.send(`Thanks for invite me!\n\nType **c!help** to see a full list of available commands!`).catch(console.error)
};
如果有帮助,这是我们的事件处理程序:
const events = fs.readdirSync('./events').filter(file => file.endsWith('.js'));
for (const file of events) {
console.log(`Loading discord.js event ${file}`);
const event = require(`./events/${file}`);
client.on(file.split(".")[0], event.bind(null, client));
};
我们正在运行 discord.js: 12.5.1
由于回调的工作方式,这在这种特殊情况下不起作用client.on("guildCreate")
。事实上,您可能会发现,由于回调如何与您使用.bind()
.
问题
想想client.on()
它的回调是如何工作的。当使用client.on()
你做这样的事情:client.on("guildCreate", callback)
。这就是client.on()
触发该事件时的作用:它调用callback(guild)
.
现在想想你在你的代码中做了什么。您正在event.bind(null, client)
处理您的事件处理程序函数,该函数采用callback(client, guild)
. 所以这就是发生的事情:
client
回调中的值设置为您的Discord.Client
, 通过.bind()
。所以现在你的client
参数是Discord.Client
,你的guild
参数是undefined
。client
) 设置为一个Guild
对象。所以现在您的client
参数是Guild
并且您的guild
参数仍然是 undefined
。guild.channels.cache
. guild
仍未定义,因此guild.channels
未定义,因此您会收到错误:Cannot read property 'cache' of undefined
。解决方案
好的,那么你如何解决这个问题?好吧,您的第一直觉可能是简单地切换回调中client
和guild
参数的顺序,然后.bind()
适当地调整您的。这可能适用于该特定事件,但请记住,某些事件在其回调中具有两个或多个参数。guildCreate
只向您发送一个公会参数,但类似的东西guildUpdate
会向您发送两个(因此导致您当前遇到的完全相同的错误)。
无论您追求什么解决方案,您都需要client
完全废弃该参数。如果您想考虑任意数量的参数并仍然使用方便的.bind()
方法,那么您可以将您的客户端绑定到this
关键字,而不是将您的客户端绑定到回调的第一个参数。这是我的意思的一个例子:
事件处理程序:
const events = fs.readdirSync('./events').filter(file => file.endsWith('.js'));
for (const file of events) {
console.log(`Loading discord.js event ${file}`);
const event = require(`./events/${file}`);
client.on(file.split(".")[0], event.bind(client));
};
guildCreate.js:
module.exports = async function (guild) {
const client = this;
const channel = guild.channels.cache.find(channel => channel.type === 'text' && channel.permissionsFor(guild.me).has('SEND_MESSAGES'))
console.log(`${client.user.username}` + `has entered` + `${guild.name}.`)
channel.send(`Thanks for invite me!\n\nType **c!help** to see a full list of available commands!`).catch(console.error)
};
这应该确保client.on()
不会干扰 的值client
,从而修复您遇到的特定错误。
改变了什么
所以总的来说,您需要:在您的事件处理程序中更改.bind(null, client)
为.bind(client)
,client
从 guildCreate.js 回调中删除参数,用于this
访问您的客户端,更改client.name
为client.user.username
因为前者不正确,并从 ES6 箭头函数 ( () => {}
) 切换到标准函数语法 ( function() {}
) 因为this
关键字在前者中的工作方式。
我还没有测试过这个解决方案,但假设它至少可以解决您当前面临的错误。如果没有,或者此代码中是否存在其他相关错误,请告诉我,我将编辑答案以修复它们。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句