Landon
Landon

Reputation: 21

Why is my discord.js channel send throwing an error?

I want to use discord.js to send messages to a certain channel. Here is the code:

const Discord = require('discord.js');

const client = new Discord.Client();

client.on('ready', () => {
 console.log('ready');
});

const channel = client.channels.cache.get('my id');
channel.send('content');

client.login(process.env.DISCORD_TOKEN);

But for some reason it throws this error:

TypeError: Cannot read property 'send' of undefined.

What am I doing wrong?

Upvotes: 0

Views: 46

Answers (1)

Jakye
Jakye

Reputation: 6645

The problem is that client.channels.cache is empty until the Client is ready.

To fix your issue, you can place your code into the ready event of Client.

const Discord = require('discord.js');

const client = new Discord.Client();

client.on('ready', () => {
 console.log('ready');
 const channel = client.channels.cache.get('my id');
 channel.send('content');
});

client.login(process.env.DISCORD_TOKEN);

Upvotes: 1

Related Questions