提问者:小点点

类型错误:无法读取未定义(读取“获取”)Discord.js v13 的属性


尝试从公会中的每个频道获取 10 条消息并读取内容,然后查看它们是否包含某个字符串,但收到以下错误

TypeError: Cannot read properties of undefined (reading 'fetch')

这是我的代码

interaction.guild.channels.cache.forEach(c => {
   c.messages.fetch({limit: 10}).then(msgs => {
      msgs.forEach(m => {
         if (m.content.includes(interaction.options.getString('text',true))) {
            // will do stuff here
         }
      }).catch(err => console.error(err))
   })
})

共1个答案

匿名用户

interaction.guild.channels.cache 是 GuildChannel 的集合。

公会频道结合了所有这些类别的频道。

遗憾的是,只有文本频道和新闻频道具有消息属性。

也许您需要在获取消息之前检查此条件。

interaction.guild.channels.cache.forEach(c => {
   if(c.type == 'GUILD_TEXT'){
      c.messages.fetch({limit: 10}).then(msgs => {
         msgs.forEach(m => {
            if (m.content.includes(interaction.options.getString('text',true))) {
               // will do stuff here
            }
         }).catch(err => console.error(err))
      })
   }
})

您还可以过滤频道

interaction.guild.channels.cache.filter((c) => c.type == 'GUILD_TEXT').forEach(c => {
   c.messages.fetch({limit: 10}).then(msgs => {
      msgs.forEach(m => {
         if (m.content.includes(interaction.options.getString('text',true))) {
            // will do stuff here
         }
      }).catch(err => console.error(err))
   })
})