'Discord Bot can't find channel by name or id
I'm trying to make a discord bot with node.js I want to post message only in specific channel I tried to do that to save a channel in a variable but that doesn't work :
const Discord = require('discord.js');
const fs = require("fs");
var bot = new Discord.Client();
var myToken = 'NDQ2OTQ1...................................................';
//client.msg = require ("./char.json");
var prefix = ("/");
//let preset = JSON.parse(fs.readFileSync('preset.json', 'utf8')); // This calls the JSON file.
var offTopic = bot.channels.find("id","448400100591403024"); //.get("448392061415325697");
console.log(offTopic);
Whenever i run my bot it returns 'null' with find and 'undefined' with get. I search for help on internet and even if i follow this post my code doesn't work : Discord Bot Can't Get Channel by Name I also tried to find my channel by name but i got 'undefined' too :/
Solution 1:[1]
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));
});
Solution 2:[2]
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
Solution 3:[3]
bot.on('ready', (message) => {
var offTopic = client.channels.cache.get("448400100591403024")
console.log(offTopic)
})
Solution 4:[4]
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.
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 | Few Tries |
| Solution 3 | Pranjal Patel |
| Solution 4 | Nabeel Khan |
