Hello I'm trying to send out an automated message to discord but I keep getting the following error:
bot.sendMessage is not a function
I'm unsure as to why I'm getting this error, below is my code;
var Discord = require('discord.js');
var bot = new Discord.Client()
bot.on('ready', function() {
console.log(bot.user.username);
});
bot.on('message', function() {
if (message.content === "$loop") {
var interval = setInterval (function () {
bot.sendMessage(message.channel, "123")
}, 1 * 1000);
}
});
Hello I'm trying to send out an automated message to discord but I keep getting the following error:
bot.sendMessage is not a function
I'm unsure as to why I'm getting this error, below is my code;
var Discord = require('discord.js');
var bot = new Discord.Client()
bot.on('ready', function() {
console.log(bot.user.username);
});
bot.on('message', function() {
if (message.content === "$loop") {
var interval = setInterval (function () {
bot.sendMessage(message.channel, "123")
}, 1 * 1000);
}
});
Share
Improve this question
edited May 17, 2017 at 17:34
Lennart
1,5605 gold badges20 silver badges38 bronze badges
asked May 17, 2017 at 16:39
fragile fragile
611 gold badge3 silver badges7 bronze badges
0
2 Answers
Reset to default 6Lennart is correct, you can't use bot.sendMessage
because bot
is a Client
class, and doesn't have the sendMessage
function. That's the tip of the iceberg. What you're looking for is send
(or the old version, sendMessage
).
These functions can't be used directly from the Client
Class (which is what bot
is, they are used on a TextChannel
class. So how do you get this TextChannel
? You get it from the Message
class. In your sample code, you aren't actually getting a Message
object from your bot.on('message'...
listener, but you should!
The callback function to bot.on('...
should look something like this:
// add message as a parameter to your callback function
bot.on('message', function(message) {
// Now, you can use the message variable inside
if (message.content === "$loop") {
var interval = setInterval (function () {
// use the message's channel (TextChannel) to send a new message
message.channel.send("123")
.catch(console.error); // add error handling here
}, 1 * 1000);
}
});
You'll also notice I added .catch(console.error);
after using message.channel.send("123")
because Discord expects their Promise
-returning functions to handle errors.
I hope this helps!
Your code is returning the error, because Discord.Client()
doesn't have a method called sendMessage()
as can be seen in the docs.
If you would like to send a message, you should do it in the following way;
var Discord = require('discord.js');
var bot = new Discord.Client()
bot.on('ready', function() {
console.log(bot.user.username);
});
bot.on('message', function() {
if (message.content === "$loop") {
var interval = setInterval (function () {
message.channel.send("123")
}, 1 * 1000);
}
});
I remend familiarising yourself with the documentation for discord.js which can be found here.