DiscordJS 无法读取 null 的属性(读取 'id')

DiscordJS Cannot read properties of null (reading 'id')

我正在尝试在有人加入 vc 并移动 vc 时进行记录,移动 vc 日志记录工作正常,但在加入 vc 时出现错误 TypeError: Cannot read properties of null (reading 'id')

module.exports = async (client, oldState, newState) => {
        if (oldState.channel && newState.channel && oldState.channel.id !== newState.channel.id) {
            const embed = new Discord.MessageEmbed()
                .setAuthor({ name: newState.member.user.tag, iconURL: newState.member.user.displayAvatarURL({ dynamic: true }) })
                .setTimestamp()
                .setColor(config.colour)
                .setFooter({ text: newState.guild.name, iconURL: newState.guild.iconURL({ dynamic: true }) })
                .setDescription(`**${newState.member} moved from \`${oldState.channel.name}\` to \`${newState.channel.name}\`**`)
            return logChannel.send({ embeds: [embed] })
        }
        if (!oldState.channel.id && newState.channel.id) {
            const embed = new Discord.MessageEmbed()
                .setAuthor({ name: newState.member.user.tag, iconURL: newState.member.user.displayAvatarURL({ dynamic: true }) })
                .setTimestamp()
                .setColor(config.colour)
                .setFooter({ text: newState.guild.name, iconURL: newState.guild.iconURL({ dynamic: true }) })
                .setDescription(`** ${newState.member} has joined \`${newState.channel.name}\` channel.**`)
            return logChannel.send({ embeds: [embed] })
        }
    }
}

第一次加入频道时,没有oldState.channel所以机器人无法获取不存在的频道id。您可以像这样编辑您的陈述;

if (oldState.channel && newState.channel && oldState.channel.id !== newState.channel.id)

if(oldState.channel && newState.channel){
if(oldState.channel.id != newState.channel.id){
 // rest of code
}
}

也许你可以做得更干净,但这就是它的工作原理。