我正在尝试编写一个机器人,该机器人会在有人加入语音通道时发送一条消息。代码和错误如下。
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
答案 0 :(得分:1)
这很容易解决。问题是voiceStateUpdate
确实有两个变量,但是它们不是oldMember, newMember
而是oldState, newState
。
与函数一样,您实际上对它们的称呼并不重要,但是使用oldState, newState
更有意义,因为它们是voiceState
。因此,它们没有voice
属性。
因此,要解决此问题,您所要做的就是使用正确的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`)
}
});