Discord Bot can't find channel by name or id

风格不统一 提交于 2020-12-10 02:54:28

问题


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


回答1:


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.




回答2:


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));
});


来源:https://stackoverflow.com/questions/50463163/discord-bot-cant-find-channel-by-name-or-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!