Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :/

like image 282
Mister Aqua Avatar asked May 22 '18 08:05

Mister Aqua


2 Answers

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.

like image 100
Silvia O'Dwyer Avatar answered Sep 17 '22 17:09

Silvia O'Dwyer


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));
});
like image 40
Taylan Avatar answered Sep 18 '22 17:09

Taylan