(discord.js v13)如果通道存在



我正在制作一个带有按钮的票务系统。我试着如果用户打开了一个票,用户不能打开一个新的票。我试了一些代码:

//ticket channel is created with **"help: " + interaction.user.username** name

if (interaction.guild.channels.fetch('channel name'))
//working with only id
if (interaction.guild.channels.cache.get(c=>c.name==='channel name'))
//reacted nothing

discord.js通道缓存是一个值的Discord.Collection,这意味着它是一个JS映射,由discord.js添加了一些额外的生活质量方法。Discord Collections使用雪花id进行键设置,其值是使用该id存储的任何对象(在本例中是您想要的通道)。这意味着通道集合上的fetch方法始终只能传递文档中所述的ID。这也意味着您在第二次尝试中尝试使用的Map.get()方法将不会返回任何内容,因为通道不是由其名称键化的,而是由雪花id键化的。

你可以使用一段代码,就像我在一个不和谐调解机器人中使用的那样,如果它存在于缓存中,则按名称查找并返回通道。

/**
* Get the log channel for the provided guild.
* @param {Discord.Guild} guild The guild to get the log channel for.
*/
#getLogChannel = (guild) => {
const guildLogChannel = guild.channels.cache
.find(channel => channel.name === 'guild-logs');
if (!guildLogChannel) return false;
return guildLogChannel;
}

如果通道还没有被缓存,你没有其他的选择,而不是将该通道作为一个选项传递到交互中,通过它的雪花id获取通道,或者获取bot在client.on('ready', () => {})处理程序中的所有公会的所有通道。最后一个选项是我选择为上面代码片段取自的bot执行的操作。

相关内容

最新更新