代码不会完美工作,我发现了几个问题:
- 当我连接到
VC
并试图尝试命令时,bot leaves the VC
但一次triggers two functions
,即常规离开功能和作者不在同一通道中 - 当我给出命令
being outside the VC
(机器人连接到VC(时,机器人用函数响应,我们不在同一个通道函数中,相反,我想要it to respond
和,你没有连接到VC - 当我在
being outside VC
和bot not connected to VC
时发出命令时,它没有响应,at console
我得到错误:
(node:37) UnhandledPromiseRejectionWarning: TypeError: cannot read property "id" of undefined
代码:
client.on('message', async (message) => {
const args = message.content.slice(prefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
if (command === 'leave') {
let authorVoice = message.member.voice;
const embed1 = new discord.MessageEmbed()
.setTitle('🚫`You are not in a Voice Channel!`')
.setColor('RED')
.setTimestamp();
if (!authorVoice.channel) return message.channel.send(embed1);
const embed2 = new discord.MessageEmbed()
.setTitle('⛔`We are not in a same Voice Channel`')
.setColor('YELLOW')
.setTimestamp();
if (authorVoice.channel.id !== client.voice.channel.id)
return message.channel.send(embed2);
const embed = new discord.MessageEmbed()
.setTitle('`Successfully left the Voice Channel`✔')
.setColor('RED')
.setTimestamp();
authorVoice.channel.leave()
message.channel.send(embed);
}
});
有人能帮我修吗?
client.voice
没有channel
属性。这意味着client.voice.channel
是未定义的。当你试图读取它的id
时,你会收到一个错误:;无法读取属性";id";未定义的"。
您可能希望connections
是VoiceConnection
s的集合。连接确实具有channel
属性,但由于client.voice.connections
是一个集合,因此需要先找到所需的。
由于您只想检查是否存在具有相同ID的通道,因此可以使用.some()
方法。在其回调函数中,您可以检查是否有任何连接的通道ID与消息作者的通道ID相同。因此,您可以创建一个返回布尔值的变量,而不是if(authorVoice.channel.id !== client.voice.channel.id)
。如果机器人在同一通道中,则返回true
,否则返回false
:
const botIsInSameChannel = client.voice.connections.some(
(c) => c.channel.id === authorVoice.channel.id,
);
// bot is not in the same channel
if (!botIsInSameChannel)
return message.channel.send(embed2);
如果有人在关注,下面是更新的代码
client.on('message', async message => {
const args = message.content.slice(prefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
if (command === 'leave') {
let authorVoice = message.member.voice;
const botIsInSameChannel = client.voice.connections.some(
(c) => c.channel.id === authorVoice.channel.id,
);
const embed1 = new discord.MessageEmbed()
.setTitle(':no_entry_sign: You are not in a Voice Channel!')
.setColor('RED')
.setTimestamp();
if(!authorVoice.channel) return message.channel.send(embed1);
const embed2 = new discord.MessageEmbed()
.setTitle(':no_entry: We are not in a same Voice Channel')
.setColor('YELLOW')
.setTimestamp();
if (!botIsInSameChannel) return message.channel.send(embed2)
const embed = new discord.MessageEmbed()
.setTitle('Successfully left the Voice Channel✔')
.setColor('RED')
.setTimestamp();
authorVoice.channel.leave();
message.channel.send(embed);
}
});