I'm trying to wrap my heading around discord.js API. It's my first API/project. I'm trying to log a channels name. The discord documentation offers this example code
// Fetch a channel by its id
client.channels.fetch('actualIdHere')
.then(channel => console.log(channel.name))
.catch(console.error);
This throws a missing access error. I have permissions enabled. Here's my setup.
// Require the necessary discord.js classes
const { Client, Intents } = require('discord.js');
const { token } = require('./config.json');
// declare intents
const myIntents = new Intents();
myIntents.add(
[
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_INTEGRATIONS,
Intents.FLAGS.GUILD_MESSAGES,
],
);
// Create a new client instance
const client = new Client({ intents: myIntents });
client.login(token);
Here's the logout (note, where are these promises coming from?)
AsyncQueue { promises: [] }
AsyncQueue { promises: [] }
DiscordAPIError: Missing Access
at RequestHandler.execute (C:\Users\name\discord-greed-game-bot\node_modules\discord.js\src\rest\RequestHandler.js:351:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (C:\Users\name\discord-greed-game-bot\node_modules\discord.js\src\rest\RequestHandler.js:52:14)
at async ChannelManager.fetch (C:\Users\name\discord-greed-game-bot\node_modules\discord.js\src\managers\ChannelManager.js:115:18) {
method: 'get',
path: '/channels/actualIdHere',
code: 50001,
httpStatus: 403,
requestData: { json: undefined, files: [] }
}
After chatting a bit with OP, it seems that the problem came from these lines of code being executed before the <Discord>.Client was ready to run commands. That's the reason why any code that has to be executed by the bot should be placed inside an event, and after the ready one has been emitted. As suggested by @Wheelwright, a workaround could be to setTimeout() that code, in order to let the bot have some time to connect, but it isn't recommended, due to API latency which, sometimes, requires more time to login.
client.once('ready', bot => {
console.log(`Ready! Logged in as ${bot.user.tag}.`);
client.channels.fetch('idOfTheChannel')
.then(channel => console.log(channel.name))
.catch(console.error);
});