Reputation: 43
I am trying to send a message to a specific channel using discord.js:
const Discord = require("discord.js");
const client = new Discord.Client();
client.login(process.env.DISCORD_TOKEN);
const channel = client.channels.cache.get("831148754181816351");
channel.send("working");
Error message:
home/fahd/Desktop/Dev/DiscordBot/main.js:7
channel.send("working");
^
TypeError: Cannot read property 'send' of undefined
at Object.<anonymous> (/home/fahd/Desktop/Dev/DiscordBot/main.js:7:9)
at Module._compile (internal/modules/cjs/loader.js:999:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
at Module.load (internal/modules/cjs/loader.js:863:32)
at Function.Module._load (internal/modules/cjs/loader.js:708:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)
at internal/main/run_main_module.js:17:47
I tried using changing the location of client.login() to the end of the file.
I tried using channels.cache.find(c => c.id === "831148754181816351");
instead but it still didn't work.
Upvotes: 0
Views: 92
Reputation: 1196
I tested out your code as-is and this means that the channels
collection it is trying to retrieve is empty.
What you have to do instead is put it inside a client event listener. From here, I learned that the compiler will always run the code outside of the client EventEmitters first before the bot is able to log in. The most convenient option (because it looks like you want this to be triggered automatically when the bot is on) is to use the ready
event listener.
Example Code:
const Discord = require("discord.js");
const client = new Discord.Client();
require('dotenv').config();
client.on('ready', () => {
const channelID = '831148754181816351'; //this is your channelID
const channel = client.channels.cache.get(channelID);
channel.send('working'); //this works :)
});
client.login(process.env.DISCORD_TOKEN);
Upvotes: 2
Reputation: 1880
Seems like you are not getting the channel you want. Try using the .fetch()
method. Since it returns a promise
you also need to await
it.
It then should look like this:
const channelID = '831148754181816351';
const targetChannel = await message.client.channels.fetch(channelID);
// work with 'targetChannel'
Upvotes: 0