Reputation: 744
I'm trying to make a discord bot with DiscordJS
I want to fetch a specific channel :
const Discord = require('discord.js');
var bot = new Discord.Client();
var myToken = 'NDQ2OTQ1...................................................';
var channelFind = bot.channels.find("id","XXXXXXXXXXX"); // null
var channelGet = bot.channels.get("id","XXXXXXXXXXX"); // undefined
Whenever I run my bot, it returns null
with find
and undefined
with get
.
I also tried to find my channel by name
Upvotes: 10
Views: 81745
Reputation: 254
Make sure you've placed your "find" line within an event listener. For example, let's say you wanted to find the specific channel when the bot connects successfully:
bot.on('ready', () => {
console.log(`Logged in as ${bot.user.tag}!`);
var offTopic = bot.channels.get("448400100591403024");
console.log(offTopic);
});
Of course, there are a huge range of event listeners available, which will suit the scenario in which you want to find the channel. You'll find event listeners in the Events section of the Client Class in the DiscordJS docs. Try this out, and let me know if it works.
Update: 2022
In discord.js v12 and above, bot.channels.get();
should now be bot.channels.cache.get();
Upvotes: 18
Reputation: 3993
You can do it either via .then promise call or via async await as explained here: .
Code will be like this (change the variable client
to your bot if needed):
let channel = await client.channels.fetch('channel-id-here')
// or you can use:
client.channels.fetch('channel-id-here').then( () => {
// do something here
})
I hope it helps both sort of scenarios.
Upvotes: 0
Reputation: 11
bot.on('ready', (message) => {
var offTopic = client.channels.cache.get("448400100591403024")
console.log(offTopic)
})
Upvotes: 0
Reputation: 23
The way you retrieve information from client changed in discordjs v12, that applies if the information was cached tho.
var offTopic = bot.channels.cache.get('448400100591403024'); //.get('448392061415325697');
console.log(offTopic);
If the information isn't cached, you will need to use the fetch method that Taylan suggested. This method uses Discord API to get the Discord object by an ID.
client.channels.fetch('448400100591403024')
.then(channel => console.log(channel.name));
You can read more about changes brought with discordjs v12 here
Upvotes: 1
Reputation: 3157
It seems like the new version of the library uses .fetch
instead of .get
and it returns a promise:
const Discord = require('discord.js');
const client = new Discord.Client();
client.on('ready', () => {
client.channels.fetch('448400100591403024')
.then(channel => console.log(channel.name));
});
Upvotes: 20