【问题标题】:Make a bot send a message to a text channel when somebody joins or leaves its voice channel当有人加入或离开其语音频道时,让机器人向文本频道发送消息
【发布时间】:2019-04-07 14:03:39
【问题描述】:

我想让我的机器人向刚刚进入其语音通道或刚刚离开其语音通道的文本通道发送消息。我是编码新手,但我已经尝试过,但它不起作用。

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) {
  }
});

控制台中甚至什么都没有显示。

【问题讨论】:

    标签: discord.js


    【解决方案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.`);
      }
    });
    

    【讨论】:

    • 如果用户已加入,我如何向文本频道发送消息?
    • 我编辑了我的答案。您需要先获取您要发送消息的频道,然后您可以使用TextChannel.send()
    • 最后一件事,我将如何获得加入的用户名。 newMemer.username 似乎不起作用
    • 我编辑了我的答案:如果您想@提及用户,请使用我现在回答中的代码(当您将 GuildMember 转换为字符串时,它会成为提及)。如果您只想使用usernametag 或其他User 属性,只需使用newMember.user -> newMember.user.usernamenewMember.user.tag 等等...
    • 非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2018-06-16
    • 2021-07-06
    • 2021-07-13
    • 2021-04-24
    • 2019-04-08
    • 1970-01-01
    • 2021-06-30
    • 2019-04-07
    相关资源
    最近更新 更多