【问题标题】:How to check if the bot is in the same channel as the user?如何检查机器人是否与用户在同一频道?
【发布时间】:2021-07-28 05:35:17
【问题描述】:

我一直在制作一个音乐不和谐机器人,我想检查用户是否与机器人在同一个语音频道中。

我尝试了以下方法,但没有成功:

let voiceBot = client.voice.connections.channel;
const voiceChannel = msg.member.voice.channel;

if(!voiceBot == voiceChannel)
  return msg.channel.send('you need to be in the same channel as the bot!')

【问题讨论】:

  • 比较 ID 而不是对象。
  • 但是等等我怎样才能得到机器人频道的ID

标签: javascript discord discord.js bots


【解决方案1】:

由于voice.connections 是连接的集合,您可以使用.some() 方法遍历这些连接并检查任何connection's channel 是否具有与channel.id 相同的channel.id

如果会员和机器人在同一个频道,.some() 方法将返回 true,否则返回 false。所以你可以这样使用它:

const inSameChannel = client.voice.connections.some(
  (connection) => connection.channel.id === msg.member.voice.channelID
)

if (!inSameChannel)
  return msg.channel.send('You need to be in the same channel as the bot!')

【讨论】:

  • 您也可以只检查msg.guild.me.voice.channelID,而不是遍历client.voice.connections。这会快得多,尤其是当机器人在多个公会中时。
【解决方案2】:
    client.voice.connections.find(i => i.channel.id === msg.member.voice.channel.id);

这将遍历机器人当前所在的语音频道列表,并根据消息作者当前语音频道的 ID 检查频道 ID。它将返回通道对象,如果没有找到,则返回 undefined。如果您只想检查 id,可以在 if 语句中使用它:

    if (!client.voice.connections.find(i => i.channel.id === msg.member.voice.channel.id)) {
        console.log("The member isn't in a shared voice channel!");
    };

或者将其定义为常量并从中获取其他信息:

    const vc = client.voice.connections.find(i => i.channel.id === msg.member.voice.channel.id);

    if (vc) { //If the channel is valid
        console.log(`The voice channel id is: ${vc.channel.id}`);
    } else { //If the channel is undefined
        console.log("The member isn't in a shared voice channel!");
    };

【讨论】:

  • 但是我怎样才能只检查机器人是否在语音频道中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-13
  • 1970-01-01
  • 2021-05-01
  • 2020-12-22
  • 2019-03-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多