在不知道确切频道的情况下搜索消息 [discord.js]

Searching for a message without knowing exact channel [discord.js]

我正在尝试通过其 ID 获取服务器上的特定邮件内容,但不知道确切的渠道。 这是我正在使用的代码:

message.guild.channels.cache.filter(c => c.type === 'GUILD_TEXT').each((c) => {
  console.log(c.messages.cache.get("ID").content)
})

但我最后得到的唯一结果是:

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

如果有人帮助我找到更好的方法来做这件事或修复我的问题,我将不胜感激!

通过条件链接或可选链接处理 .get() 返回未定义的可能性。

message.guild.channels.cache.filter(c => c.type === 'GUILD_TEXT').each((c) => {
  console.log(c.messages.cache.get("ID")?.content)

// Or

   if (c.messages.cache.get("ID")) {     
     console.log(c.messages.cache.get("ID").content);
   }
})

我推荐一种不同的方法。要获得更易读的代码,请使用一些变量,然后使用 find() 方法。

const textChannel = message.guild.channels.cache
   .filter(c => c.type === 'GUILD_TEXT')
   .find(c => c.messages.cache.has('ID'));
if (!textChannel) return console.log("No result");

const msg = textChannel.messages.cache.get('ID');

console.log(msg.content);

这就是我发现的工作...

message.guild.channels.cache.filter(c => c.type === 'GUILD_TEXT').each(async c => {
  let getMsg = async () => { 
    let msg = await c.messages.fetch(/* ID HERE */).catch(err => err)
    return msg
  }
  getMsg().then(msg => {
    if(msg.content !== undefined){
      console.log(msg.content)
      message.reply(`
        Content: **${msg.content}**\n\n
        Author: **<@${msg.author.id}>**\n\n
        Channel: **<#${msg.channel.id}>**
      `)
    }
  })
})

这是如何工作的...

问题...

You were trying to parse large amounts of data in a very quick time, much faster than discord's api will allow you to. So I made a async function to return the message at a pace that discord allows you to without error.

getMsg()函数...

Inside of the getMsg() function, I awaited a fetch to all the channels. the .catch() function at the end is crucial otherwise this will end your process with an error code.

正在调用函数...

I then called the function and awaited it to finish then checked if the message.content it got was undefined, because for some odd reason if I don't it will throw an error, I believe it is because it is trying to log every channels return on the message and not every channel was able to fetch it which causes the error.

额外...

I also added it to reply to you with the message content, the author, and the channel as well just to give you an idea of what you can access with the returned message, but that is easily removable if you don't want that.


虽然没有优化到令人惊奇的地步,但它可以满足您的要求:)