Sending a message 5 minutes after a command - javascript

So im trying to do my discord bot send a message 5 minutes after someone send a command, but when someone use the command it start sending the message every minute, thats the code
client.on('message', function(message) {
if (message.content === "!command") {
var interval = setInterval (function () {
client.channels.get("493228844896092162")
.send("123")
.catch(console.error);
}, 1 * 5000);
}
});

Your interval seems to be incorrect. setInterval expects interval to be in milliseconds.
1 * 5000 -> 5sec
You need to update that to
5 * 60 * 1000 -> 5 mins

setInterval takes the arguments of a function and a set number of milliseconds on which to trigger.
The correct interval would be
setInterval(function(){}, 5 * 60000)
This is 5x60 seconds

I'd code it like this:
client.on('message', function(message) {
if (message.content === "!command") {
var interval = setInterval (function () {
try {
var meme = client.channels.get("493228844896092162")
meme.send("123")
} catch (error) {
console.log(error.stack);
}, 5 * 60000);
}
});

Related

Discord.js Ping Pong command with cooldown

I'm very new to coding so it's probably horrible. Here's the code
let userCooldown = {};
client.on("message", message => {
if (message.content.includes('ping'))
if (userCooldown[message.author.id]) {
userCooldown[message.author.id] = false;
message.reply('Pong');
setTimeout(() => {
userCooldown[message.author.id] = true;
}, 5000) // 5 sec
}
})
the plan would be for the bot not to respond to the message for 5 seconds until it's written again
Not sure why you set the cooldown to false if it's true when someone sends a message and why you set it to true after five seconds.
If your userCooldown includes the users who currently can't execute the function, you need to check if they are already on that list. If they are, don't execute the function. If they are not, execute the function, add them to the list and use setTimeout to remove them after five seconds. Try to run the snippet below:
let userCooldown = {};
function onMessage(message) {
console.log(`onMessage fired with message: "${message.content}"`);
if (message.content.includes('ping')) {
// if user can't execute the fucntion, just exit
if (userCooldown[message.author.id]) return;
// if they can, add them to userCooldown
userCooldown[message.author.id] = true;
console.log('Pong!');
// and remove them after 5 seconds
setTimeout(() => {
userCooldown[message.author.id] = false;
}, 5000);
}
}
// run it every second to test it :)
let message = { content: '!ping', author: { id: 'authorID' } };
setInterval(() => onMessage(message), 2000)

Issue with code - message is sent instantly instead of waiting for timeout to happem

An issue with the code - the message is sent instantly instead of waiting for the timeout to happen.
As seen in the code it should take the time mentioned in the message.
I don't understand what is happening that doesn't allow it to work at all.
client.on("message", async (message) => {
timer = false;
if (message.content.startsWith("timer")) timer = true;
if (timer === true) {
timewait = message.content.slice(6);
integertime = parseInt(timewait);
mili = integertime * 60000;
setTimeout(message.channel.send("messgae"), mili);
}
});
The problem is you're invoking the function inside setTimeout, so it will run immediately. You can create a new function that returns your function like this:
setTimeout(() => message.channel.send("message"), mili);
This way you pass a function instead of a value.
setTimeout needs a function passed. setTimeout(function, milliseconds)
Try out doing setTimeout(function(){ message.channel.send("messgae"); }, mili);
Maybe you are looking for something like this:
client.on("message", async (message) => {
if (message.content.startsWith("timer")){
let MessageArray = message.content.slice().trim().split(" ") // Creats an Array by seperating the Message into the Array
let integertime = parseInt(MessageArray[1]); // Taking the second Input of your Message and parsing it into an Integer
let mili = integertime * 60000
setTimeout(function(){
message.channel.send("message")
}, mili) // Sends the Message by using the second Input you've given in your command multiplied by your value in mili as your value for the Timer.
}
})
See setTimeout() in the MDN Documentation.

How to add setTimeout to this code for 1 minute?

how could i add a 1 minute timeout to this code before it answers?
//cd test
client.on("message", (msg) => {
if(msg.content.toLowerCase().startsWith(`${PREFIX}1cd`)) {
let user = message.mentions.roles.first();
message.channel.send(`1 minute has passed <#${msg.author.id}>`)
}
});
//cd test
Like this:
setTimeout(() => {
// Code goes here
}, 60000)
See setTimeout()
https://www.w3schools.com/jsref/met_win_settimeout.asp
client.on("message", (msg) => {
if(msg.content.toLowerCase().startsWith(`${PREFIX}1cd`)) {
//pass the code that you want to execute later as a callback function
setTimeout(() => {
let user = message.mentions.roles.first();
message.channel.send(`1 minute has passed <#${msg.author.id}>`)
}, 60000); //60s is 60000 ms, and it takes the amount of time as milliseconds
}
});

Set Timeout running 4 times each minute

for some reason a function I would like to execute every minute is running 4 times every minute. I would like the behavior to only fire a single time. I am unsure of why it is firing multiple times. the code is as follows:
const checkToken = () => {
console.log('im running')
const token = localStorage.FBIdToken
if (token && token !== 'Bearer undefined') {
const decodedToken = jwtDecode(token)
if (decodedToken.exp * 1000 < Date.now()) {
localStorage.removeItem('FBIdToken')
window.location.reload()
}
}
setTimeout(checkToken, 60 * 1000)
}
checkToken()
you are using this script in react, so make sure that this function/method is not triggering with component re-rendering. if you are using stateful component then move this function to componentDidMount to stop the multiple calls to this method. and if you are using stateless component then use hooks to avoid this issue
you can also use the clearInterval to avoid this issue
const timeInterVal = null;
const checkTokenFunc = () => {
if (token && token !== 'Bearer undefined') {
const decodedToken = jwtDecode(token)
if (decodedToken.exp * 1000 < Date.now()) {
localStorage.removeItem('FBIdToken')
window.location.reload()
}
}
}
const checkToken = () => {
if(timeInterval!==null){
clearTimeout(timeInterval);
}
timeInterval = setTimeout(() => {
checkTokenFunc();
checkToken();
}, 60 * 1000)
}
checkToken();
You could use setInterval() instead of setTimeout(). setInterval() you can specify a period of time and it will keep running based on the time interval you set...Pass setInterval() a function to execute and a time interval in milliseconds. The below will execute every 5 seconds.
Example:
setInterval(function(){ alert("Hello"); }, 5000);

Retry count and interval

How do I write script If a communication error is received, function shall by default, retry up to 3 times with a 15 second interval between re-tries. Whether a retry on a communication error is performed, the number of retries and the wait interval between tries shall be client configurable parameters. Please help me on this.
You can simply add a variable like FailedCounts and work with it.
Something like:
var failedCounts = 0, myInterval;
myInterval = setInterval(function() {
if (operationFailed) {
failedCounts++;
if (failedCounts >= 3) {
clearInterval(myInterval); // probably, you may want to disable timer on failure
alert('Failed 3 times');
}
} else {
failedCount = 0;
}
}, 15000);

Categories

Resources