排序
GuildChannel.position
和的问题GuildChannel.calculatedPosition
是返回的位置是基于通道的类型。例如,所有类别都被排序并与文本通道分开分配编号,文本通道与语音通道分开。
为了解决这个问题,我们可以制作我们自己的系统来利用它来发挥我们的优势。我们首先对所有类别进行排序并将其添加到与其子项的排序集合配对的集合中。然后,我们遍历并将通道添加到列表中。
格式化
从技术上讲,该#
符号应该位于非文本频道的前面,因为 Discord 会将他们的提及转换为使用它。但是,它看起来不是很吸引人,逻辑似乎有点缺陷。
如果它不是文本频道,我们所要做的就是使用频道的名称而不是提及它。
编码
您可能需要更改一些变量,并根据需要实现嵌入。这只是一个例子。
const guild = message.guild;
// Comparison function which sorts channels according to appearance within Discord. Name
// is short for 'descending position,' but it also accomodates for voice channel location.
const descPos = (a, b) => {
if (a.type !== b.type) {
if (a.type === 'voice') return 1;
else return -1;
} else return a.position - b.position;
};
// Create a new Collection to hold categories and their children.
const channels = new Discord.Collection();
// Non-category channels without parent categories will appear at the top.
channels.set('__none', guild.channels.filter(channel => !channel.parent && channel.type !== 'category').sort(descPos));
// Add all the categories in order, mapped by their bolded name, into the Collection.
const categories = guild.channels.filter(channel => channel.type === 'category').sort(descPos);
categories.forEach(category => channels.set(category.id, category.children.sort(descPos)));
const list = [];
// Iterate through the categories and the corresponding Collection of their channels.
for (let [categoryID, children] of channels) {
// Retrieve the category from it's ID.
const category = guild.channels.get(categoryID);
// Push the category name (bolded for readability) into the list.
if (category) list.push(`**${category.name}**`);
// Iterate through the Collection of children. Push the mention for text, name for others.
for (let [, child] of children) list.push(child.type === 'text' ? child : child.name);
// To answer your comment about adding the emoji for voice channels...
// list.push(child.type === 'text' ? child : ` ${child.name}`);
}
// Send the list of channels, appearing exactly how it does on the side. Make sure the
// joined list isn't too long for a message or embed field first to avoid an error.
message.channel.send(list.join('\n'))
.catch(console.error);
资源
Discord.js 文档: