I wan't my bot to answer the "!help" command that people will type on chat but only once every 60 seconds
require('dotenv').config();
const tmi = require('tmi.js');
const client = new tmi.Client({
channels: [ 'test' ],
identity: {
username: process.env.TWITCH_BOT_USERNAME,
password: process.env.TWITCH_OATH_TOKEN
}
});
client.connect();
client.on('message', (channel, tags, message, self) => {
const send = message === "!help"
if ( !send ) return;
{
client.say(channel, `This message shouldn't send more then once eveyr 60 seconds`)
}
console.log(`${tags['display-name']}: ${message}`);
}); ```
You can use new Date() to get the current datetime. And new Date().getTime() gives you a number of milliseconds since epoch (since 1970-01-01 00:00:00 UTC).
// get the current time
const timeNow = new Date().getTime()
Every time you send a '!help' response you save the current time.
// the time of the last help message
let lastHelpTime = 0
// ... later when sending the message
// update the last help message time
lastHelpTime = timeNow
On every '!help' command you compare timeNow against the saved value lastHelpTime to avoid sending again within a minute. To allow a new response the time difference timeNow - lastHelpTime must be greater than 60 seconds, but because we have to compare milliseconds, it means the difference must be greater than 60 * 1000 milliseconds.
// check if at least 1 minute has elapsed since the last help message
if (timeNow - lastHelpTime > 60 * 1000) //...
Combined all together in your original code
// the time of the last help message
let lastHelpTime = 0
client.on('message', (channel, tags, message, self) => {
const send = message === "!help"
if ( !send ) return;
// get the current time
const timeNow = new Date().getTime()
// check if at least 1 minute has elapsed since the last help message
if (timeNow - lastHelpTime > 60 * 1000) {
// update the last help message time
lastHelpTime = timeNow
// post the help message in chat
client.say(channel, `This is the help message`)
}
console.log(`${tags['display-name']}: ${message}`);
});