Discord.js无法读取属性
我正在尝试编写一个机器人,当有人加入语音频道时,它将发送消息。代码和错误如下Discord.js无法读取属性,discord,discord.js,Discord,Discord.js,我正在尝试编写一个机器人,当有人加入语音频道时,它将发送消息。代码和错误如下 const Discord = require("discord.js"); const config = require("./config.json"); const bot = new Discord.Client(); bot.login(config.BOT_TOKEN); bot.once('ready', () => { console.log(
const Discord = require("discord.js");
const config = require("./config.json");
const bot = new Discord.Client();
bot.login(config.BOT_TOKEN);
bot.once('ready', () => {
console.log(`Bot ready, logged in as ${bot.user.tag}!`);
})
bot.on('voiceStateUpdate', (oldMember, newMember) => {
const newUserChannel = newMember.voice.channelID
const oldUserChannel = oldMember.voice.channelID
const textChannel = message.guild.channels.cache.get('766783720312537089')
if (newUserChannel === '764231813248843806') {
textChannel.send(`${newMember.user.username} (${newMember.id}) has joined the channel`)
} else if (oldUserChannel === '764231813248843806' && newUserChannel !== '764231813248843806') {
textChannel.send(`${newMember.user.username} (${newMember.id}) has left the channel`)
}
})
错误:
TypeError: Cannot read property 'channelID' of undefined
这很容易解决。问题是,
voiceStateUpdate
确实包含两个变量,但它们不是oldMember、newMember
,而是oldState、newState
与通常的函数一样,调用它们并不重要,但使用oldState、newState更为合理,因为它们是一个函数。因此,它们没有语音
属性
所以要解决这个问题,您所要做的就是使用正确的voiceState属性
const newUserChannel = newState.channelID;
const oldUserChannel = oldState.channelID;
注意:newState.user
也不是一个东西,但是它确实为您提供了member
对象,因此我建议您改用它
编辑:您的整个代码应该看起来有点像这样
bot.on('voiceStateUpdate', (oldState, newState) => {
const newUserChannel = newState.channelID;
const oldUserChannel = oldState.channelID;
const textChannel = newState.guild.channels.cache.get('766783720312537089');
if (newUserChannel === '764231813248843806') {
textChannel.send(`${newState.member.user.username} (${newState.id}) has joined the channel`)
} else if (oldUserChannel === '764231813248843806' && newUserChannel !== '764231813248843806') {
textChannel.send(`${newState.member.user.username} (${newState.id}) has left the channel`)
}
});
我现在收到了这个错误:“ReferenceError:newState未定义”您是否更改了函数顶部的名称?啊,我已经修复了这个问题,但现在收到了这个错误:“ReferenceError:message未定义”是的,因为您没有message
对象。但是,您可以通过您确实有权访问的voiceState
对象访问guild
对象。您能否用正确的代码更新您的答案,以便我将其标记为答案