I want to make interval message discord bot

Vblacqe picture Vblacqe · Sep 24, 2019 · Viewed 7.7k times · Source

I want to make that discord bot will send message interval for ex. in 10 minutes but it throws error! Please help me! (sorry for my english it is not perfect)

Here is code:

const Commando = require('discord.js-commando');
const bot = new Commando.Client({commandPrefix: '$'});
const TOKEN = 'here is token';
const MIN_INTERVAL = 100;

bot.registry.registerGroup('connectc', 'Connectc');
bot.registry.registerGroup('defaultc', 'Defaultc');
bot.registry.registerDefaults();
bot.registry.registerCommandsIn(__dirname + "/commands")

bot.on('ready', function(){
    console.log("Ready");
});
setInterval(function(){
    var generalChannel = bot.channels.get("542082004821213197"); // Replace with known channel ID
    generalChannel.send("Hello, world!") ;
}, MIN_INTERVAL);

bot.login(TOKEN);

And it throws this error

PS C:\Users\User\Documents\Visual Studio Code\Discord Bots\VblacqeBot> node .
C:\Users\User\Documents\Visual Studio Code\Discord Bots\VblacqeBot\index.js:18
    generalChannel.send("Eldo!") ;
                   ^

TypeError: Cannot read property 'send' of undefined
    at eldo (C:\Users\User\Documents\Visual Studio Code\Discord Bots\VblacqeBot\index.js:18:20)
    at Object.<anonymous> (C:\Users\User\Documents\Visual Studio Code\Discord Bots\VblacqeBot\index.js:28:13)
    at Module._compile (internal/modules/cjs/loader.js:689:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
    at Module.load (internal/modules/cjs/loader.js:599:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
    at Function.Module._load (internal/modules/cjs/loader.js:530:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:743:3)
PS C:\Users\User\Documents\Visual Studio Code\Discord Bots\VblacqeBot> 

Answer

Xan picture Xan · Sep 24, 2019

You are probably trying to do that before the bot is ready - because the interval is actually in milliseconds.

  1. Make the interval correct:

    const MIN_INTERVAL = 10 * 60 * 1000;
    // 10 minutes, 60 seconds in a minute, 1000 milliseconds in a second
    
  2. Make sure to start your interval only after the bot is ready:

    bot.on('ready', function(){
      console.log("Ready");
      setInterval(/* ... */);
    });
    

As an aside, you should use interval methods defined on the Client - they guarantee that they are cancelled if the client is destroyed:

bot.setInterval(/*...*/);

See https://discord.js.org/#/docs/main/master/class/BaseClient - Commando's client extends that.