Joaquin Parada
Joaquin Parada

Reputation: 47

Start bot with one message and end with other command

I'm basically creating a bot that does a loop, and I want it to end when you say *parar but i don't know how to make it.

Here is a bit of code to explain my problem

module.exports = {
    name: 'epico',
    execute(message, args, Discord, client){

    //this is the loop
    var interval = setInterval(function(){...}, 1000)

}

The loop starts when I put *epico and I want it to stop when user sends *parar

I was trying something like this:

client.on('message', message =>{
    if(message.content.startsWith('parar')){clearInterval(interval)}
}

But this keeps working until I shut down the bot (I want it to just work 1 time)

Upvotes: 0

Views: 184

Answers (2)

Behemoth
Behemoth

Reputation: 9310

Try something like the following: Basically what you want to do is save your interval to a variable that is accessible later on in order to stop your interval again.

const Discord = require("discord.js");
const client = new Discord.Client();

let interval;

client.on("message", async (message) => {
  if (message.content.startsWith("*epico")) {
    return (interval = setInterval(() => {
      console.log("do something");
    }, 1000));
  }

  if (message.content.startsWith("*parar")) {
    clearInterval(interval);
    return console.log("stopped interval");
  }
});

client.login("your-token");

I assume your are using multiple commands in several different files. If that is the case I would simply save the interval to the client object in your *epico command file since you pass the client to your execute function anyways.

module.exports = {
  name: "epico",
  execute(message, args, Discord, client) {
    return (client.interval = setInterval(() => {
      console.log("do something");
    }, 1000));
  },
};

And then just clear the interval in your *parar command. Also don't forget to check if client.interval is even set ;)

module.exports = {
  name: "parar",
  execute(message, args, Discord, client) {
    client.interval && clearInterval(client.interval);
    return console.log("stopped interval");
  },
};

Upvotes: 1

Oguz Turkay
Oguz Turkay

Reputation: 25

maybe you have a typo???

client.on('message', message => {
    if (message.content.startsWith('parar')){
        clearInterval(interval)
    }
});

Upvotes: 0

Related Questions