如何在 discord 中获取频道的 channel_id?

How do I get the channel_id of a channel in discord?

我正在尝试使用 node.js 创建一个 discord 机器人。我希望机器人发送欢迎信息。目前我从discord复制了欢迎频道的channel_id。虽然我想编写代码来通过名称获取欢迎频道的 ID。 (或者如果有另一种更有效的方法)。使用 discord.js v13.

使用 Guild.channels 获取服务器中 channel 的列表,然后使用 the fetch() method 遍历它们以找到具有匹配名称的 channel

获取公会的频道,然后在缓存中按名称查找

<Guild>.channels.fetch().then(channels => channels.cache.find(c=> c.name === "channel_name_here"))

使用 Guild#channels 从缓存中获取频道。其中包括一个 cache 属性,其中包含机器人可以在其中看到的所有频道 [1]。对它使用find()方法,比较name

// remember channel names can only be lowercase and have no spaces
const channel = guild.channels.cache.find(channel => channel.name === "channel-name");
console.log(channel.id) 

这里的一个缺点是多个频道可以有相同的名称,这与 ID 不同,这就是为什么人们更喜欢使用 ID 而不是名称或其他属性的原因

[1]:默认缓存所有通道,所以不需要从API

中获取