【问题标题】:Discord.JS: How to get first channel of a guild?Discord.JS:如何获得公会的第一个频道?
【发布时间】:2020-09-03 23:11:37
【问题描述】:

我正在创建一个 Discord 机器人。我想通过公会 ID 创建邀请。创建邀请需要一个频道。我想机器人选择第一个频道。我该怎么做?

我用过这个但是没用:

guild.channels[Object.keys(guild.channels)[0]]
//returns undefined

【问题讨论】:

    标签: node.js discord.js


    【解决方案1】:

    v12 试试

    var chx = guild.channels.cache.filter(chx => chx.type === "text").find(x => x.position === 0);
    

    【讨论】:

      【解决方案2】:

      如果您的意思是首先按位置,您可以使用公会频道集合按类型和位置查找频道。

      const channel = guild.channels.filter(c => c.type === 'text').find(x => x.position == 0);
      

      【讨论】:

        【解决方案3】:

        我不知道你说的第一个频道是什么意思,但你可以用这个:

        const randomChannel = (guild) => {
            guild.channels.random().then(channel => {
                if (channel.type === 'text') return channel;
                else return randomChannel(guild);
            }
        }
        

        【讨论】:

        • 这不是用户要求的,他想访问在左侧频道列表中显示最高的频道,而不是随机频道。
        【解决方案4】:

        要获得创建邀请的频道,您可能应该只使用机器人有权访问的频道,例如:

         const invitechannels = guild.channels.filter(c=> c.permissionsFor(guild.me).has('CREATE_INSTANT_INVITE'));
         invitechannels.random().createInvite()
             .then(invite=> console.log('Create Invite:\n' + invite.code))
        

        或者,您也可以检查现有邀请:

        guild.fetchInvites()
            .then(invites => console.log('Found Invites:\n' + invites.map(invite => invite.code).join('\n')))
        

        【讨论】:

          【解决方案5】:

          每个频道都有一个calculatedPosition 属性,您可以使用它来获取第一个频道。

          const channel = Array.from(guild.channels).sort((a,b) => a.calculatedPosition - b.calculatedPosition)[0];
          

          好吧,让我们分解一下上面代码中发生的事情:

          Array.from(guild.channels) //returns an Array of GuildChannels (Textchannels and Voicechannels)
          .sort((a,b) => a.calculatedPosition - b.calculatedPosition) //sorts the elements in the collection by their calculatedPosition property in ascending order and returns the array
          [0] //returns the first element of the array
          

          【讨论】:

            猜你喜欢
            • 2020-12-12
            • 1970-01-01
            • 1970-01-01
            • 2021-04-27
            • 2021-11-01
            • 1970-01-01
            • 1970-01-01
            • 2018-12-29
            • 2021-08-14
            相关资源
            最近更新 更多