我正在尝试为不和谐机器人 (js) 制作离开/断开 VC 命令,我面临着下面讨论的一些问题



代码不会完美工作,我发现了几个问题:

  1. 当我连接到VC并试图尝试命令时,bot leaves the VC但一次triggers two functions,即常规离开功能作者不在同一通道中
  2. 当我给出命令being outside the VC(机器人连接到VC(时,机器人用函数响应,我们不在同一个通道函数中,相反,我想要it to respond,你没有连接到VC
  3. 当我在being outside VCbot 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";未定义的"。

您可能希望connectionsVoiceConnections的集合。连接确实具有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);
}
});

最新更新