Send a message with Discord.js

Gabe picture Gabe · Jul 15, 2017 · Viewed 80.7k times · Source

I am trying to make a discord bot, but I can't quite understand Discord.js. My code looks like this:

client.on('message', function(message) {
 if (message.content === 'ping') {
  client.message.send(author, 'pong');
 }
});

And the problem is that I can't quite understand how to send a message.

Can anybody help me ?

Answer

Arct picture Arct · Jul 17, 2017

You have an error in your .send() line. The current code that you have is used in an earlier version of the discord.js library, and the send function has been changed.

To send a message, use this line:

message.channel.send('My Message')

If you get an error saying that message is not defined, make sure that you have put the line in your message event handler.

client.on("message", function(message) {
  //message sending goes here
});

You can also send a message to a specific channel, which you can do using the line below.

client.channels.get(channelID).send('My Message');

Or if you prefer, a guild's default channel (the #general channel that was made when the guild was created)

guildObj.defaultChannel.send('My Message');

Hope this helped,

- Spy