Me8s
Me8s

Reputation: 25

How do you find a channel using its name in Discord.js?

I tried using this to find a channel named "information" and to send a message in it:

let channel = message.guild.channels.cache.find(channel => channel.name.toLowerCase() === 'information')
channel.send('test')

And using that code resulted in this error:

let channel = message.guild.channels.cache.find(channel => channel.name.toLowerCase() === 'information')
                                               ^

TypeError: message.guild.channels.cache.find is not a function

I tried npm install discord.js to update the package, but it still didn't work. I also tried client.channels.cache.find, But it ended up receiving the same error. Am I doing something wrong here?

Upvotes: 2

Views: 8716

Answers (2)

Paniboi.Dev
Paniboi.Dev

Reputation: 11

You have to write it like this:

let channel = message.channel.guild.channels.cache.find((channel) => channel.name.toLowerCase() === `information`

I think it didn't work because you need brackets around the variable channel.

Upvotes: 0

gui3
gui3

Reputation: 1867

According to the docs you're doing it right ... but according to reddit, there is no need to call cache and you can just call :

let channel = message.guild.channels.find(
  channel => channel.name.toLowerCase() === "information"
)

this corresponds to what i am doing with my bot, and this worked a few months ago

guild.channels.array().filter(c => c.name === 'General')

Seems like guild.channels is already a collection, don't know if it's a mistake in the Documentation or if it's a really recent version that changed that ...

[edit] found the problem

in the documentation, there are two versions (up in the toolbar) v12 (default) and v11

it seems like they added the .cache in the v12, but maybe this one is not on npm already.

they have an alert about breaking changes that links to this page where they explain how to switch to v12 https://discordjs.guide/additional-info/changes-in-v12.html

Upvotes: 2

Related Questions