提问者:小点点

当某人加入或离开语音频道时,使机器人向文本频道发送消息


我想让我的机器人发送消息到一个文本频道与谁刚刚进入它的语音频道或刚刚离开它的语音频道。我对编码是新手,但是我尝试过这个,但是它不起作用。

bot.on('voiceStateUpdate', (oldMember, newMember) => {
  let newUserChannel = newMember.voiceChannel;
  let oldUserChannel = oldMember.voiceChannel;
  if (oldUserChannel === undefined && newUserChannel !== undefined) {
    if (newUserChannel === bot.voiceChannel) {
      console.log("Hello");
    }
  } else if (newUserChannel === undefined) {
  }
});

控制台中甚至没有显示任何内容。


共1个答案

匿名用户

我认为这不起作用,因为您使用的是bot.VoiceChannel,但它并不存在:.VoiceChannelGuildMember的属性,因此您需要先获取成员。
我会这样做:

bot.on('voiceStateUpdate', (oldMember, newMember) => {
  // Here I'm storing the IDs of their voice channels, if available
  let oldChannel = oldMember.voiceChannel ? oldMember.voiceChannel.id : null;
  let newChannel = newMember.voiceChannel ? newMember.voiceChannel.id : null;
  if (oldChannel == newChannel) return; // If there has been no change, exit

  // Here I'm getting the bot's channel (bot.voiceChannel does not exist)
  let botMember = oldMember.guild.member(bot.user),
    botChannel = botMember ? botMember.voiceChannel.id : null;

  // Here I'm getting the channel, just replace VVV this VVV with the channel's ID
  let textChannel = oldMember.guild.channels.get('CHANNEL_ID_HERE');
  if (!textChannel) throw new Error("That channel does not exist.");

  // Here I don't need to check if they're the same, since it would've exit before
  if (newChannel == botChannel) {
    // console.log("A user joined.");
    textChannel.send(`${newMember} has joined the voice channel.`);
  } else if (oldChannel == botChannel) {
    // console.log("A user left.");
    textChannel.send(`${newMember} has left the voice channel.`);
  }
});