【问题标题】:Discord JS - TypeError: Cannot read property 'setChannel' of undefinedDiscord JS - TypeError:无法读取未定义的属性“setChannel”
【发布时间】:2021-03-29 18:19:28
【问题描述】:

我正在尝试使用多个用户提及,而 message.mention.members.first() 无法做到这一点。所以我做了一些挖掘,从Parsing Mention Arguments找到了这个函数:

function getUserFromMention(mention) {
    if (!mention) return;

    if (mention.startsWith('<@') && mention.endsWith('>')) {
        mention = mention.slice(2, -1);

        if (mention.startsWith('!')) {
            mention = mention.slice(1);
        }

        return client.users.cache.get(mention);
    }
}

当我尝试使用此功能时,我得到“Discord JS - TypeError: Cannot read property 'setChannel' of undefined”这是导致错误的代码

            let channel = client.channels.cache.find(channel => channel.name === args[0]);
            const user1 = getUserFromMention(args[1]);
            const user2 = getUserFromMention(args[2]);
            message.member.voice.setChannel(channel.id);
            user1.voice.setChannel(channel.id);
            user2.voice.setChannel(channel.id);

此代码旨在将我自己和提及的用户移动到选定的语音频道,它在使用 message.mention.members.first() 时工作得非常好,但只能处理提及的用户中的二分之一。

我想知道是否可以修复我当前的错误,或者是否有其他方法可以解决这个问题?

【问题讨论】:

    标签: node.js discord discord.js bots


    【解决方案1】:

    问题可能是,用户不在缓存中,所以你必须使用GuildMemberManager#fetch(id)。问题是,这个函数是异步的。最简单的解决方案是使 getUserFromMention 和使用它的函数异步并使用 await。

    【讨论】:

      【解决方案2】:

      记住,

      message.mentions.members- 返回GuildMember
      client.users.cache.get - 返回User

      您只能在 VC 之间移动/断开GuildMembers

      因此,您可以使用message.mentions.members,它返回所有提及用户的Collection

      let channel = client.channels.cache.find(channel => channel.name === args[0]);
      message.member.voice.setChannel(channel.id);
      message.mentions.members.each(u => {
          u.voice.setChannel(channel.id);
      })
      

      【讨论】:

      • 啊,好的,每天都学点新东西,谢谢。
      猜你喜欢
      • 1970-01-01
      • 2021-01-19
      • 2020-10-15
      • 1970-01-01
      • 2021-01-01
      • 2021-08-29
      • 1970-01-01
      • 2021-03-31
      • 2021-09-26
      相关资源
      最近更新 更多