简体   繁体   中英

Discord.js sending a message in 1 minute intervals

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); 
    }
});

Lennart 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 recommend familiarising yourself with the documentation for discord.js which can be found here .

If I try to do this it send the message a thousand times.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM