'Searching for a message without knowing exact channel [discord.js]
I'm trying to get specific message content on the server by its ID, but without knowing exact channel. This is the code I'm using:
message.guild.channels.cache.filter(c => c.type === 'GUILD_TEXT').each((c) => {
console.log(c.messages.cache.get("ID").content)
})
but the only thing I get in the end is:
TypeError: Cannot read properties of undefined (reading 'content')
I'd really appreciate if someone helps me to find more optimal way to do it or to fix mine!
Solution 1:[1]
Handle the possibility of .get()
returning undefined, either with a conditional or optional chaining.
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);
}
})
I'd recommend a different approach. For more readable code use some variables, then use the find()
method.
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);
Solution 2:[2]
Interestingly for anyone reading this. If I use PowerShell Runbook with Runtime set to 7.1 (Preview) the script works.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Oliver Bayes-Shelton |