【发布时间】:2020-09-03 23:11:37
【问题描述】:
我正在创建一个 Discord 机器人。我想通过公会 ID 创建邀请。创建邀请需要一个频道。我想机器人选择第一个频道。我该怎么做?
我用过这个但是没用:
guild.channels[Object.keys(guild.channels)[0]]
//returns undefined
【问题讨论】:
标签: node.js discord.js
我正在创建一个 Discord 机器人。我想通过公会 ID 创建邀请。创建邀请需要一个频道。我想机器人选择第一个频道。我该怎么做?
我用过这个但是没用:
guild.channels[Object.keys(guild.channels)[0]]
//returns undefined
【问题讨论】:
标签: node.js discord.js
v12 试试
var chx = guild.channels.cache.filter(chx => chx.type === "text").find(x => x.position === 0);
【讨论】:
如果您的意思是首先按位置,您可以使用公会频道集合按类型和位置查找频道。
const channel = guild.channels.filter(c => c.type === 'text').find(x => x.position == 0);
【讨论】:
我不知道你说的第一个频道是什么意思,但你可以用这个:
const randomChannel = (guild) => {
guild.channels.random().then(channel => {
if (channel.type === 'text') return channel;
else return randomChannel(guild);
}
}
【讨论】:
要获得创建邀请的频道,您可能应该只使用机器人有权访问的频道,例如:
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')))
【讨论】:
每个频道都有一个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
【讨论】: