0

I'm trying to do a discord bot that listens to multiple twitch chat for commands, then run them on discord, using both tmi.js and discord.js. Currently it is working, but I can't seem to add a global cooldown on the commands itself to prevent spamming. At first I've tried adding a cd timer to each command, but I'm unable to get it working, hence the decision to try to make a global cd but still to no avail. Am I doing something wrongly?

twitch.on('message', (channel, tags, message, self) => {
    if(!message.startsWith(prefix) || self) return;
    const args = (message.slice(prefix.length).trim().split(/ +/));
    const commandName = args.shift().toLowerCase();
    
    if (!twitch.commands.has(commandName)) return;
    const command = twitch.commands.get(commandName);
}
    try {
        command.execute(bot, botChannel, vcChannel, isReady);
    } catch (error){
        console.error(error);
    }
        
});
  • You can implement a [throttle function](https://www.30secondsofcode.org/js/s/throttle) to limit the number of calls every X milliseconds. – Brian Lee Nov 14 '20 at 09:26
  • I've tried to implement the said throttle function at the try catch area, but it made it not work instead. Am i missing something? – sengjung123 Nov 14 '20 at 16:25

1 Answers1

0

just to update, I basically took a leaflet from async await functions here: https://stackoverflow.com/a/54772517/14637034 Then, I modified the code as such:

const setAsyncTimeout = (cb, timeout = 0) => new Promise(resolve => {
    setTimeout(() => {
        cb();
        resolve();
    }, timeout);
});
const doStuffAsync = async () => {
    await setAsyncTimeout(() => {
        isReady = true;
        console.log(isReady);
    }, 10000);};

twitch.on('message', (channel, tags, message, self) => {
    if(!message.startsWith(prefix) || self) return;
    const args = (message.slice(prefix.length).trim().split(/ +/));
    const commandName = args.shift().toLowerCase();
    
    if (!twitch.commands.has(commandName)) return;
    if (isReady){
        const command = twitch.commands.get(commandName);
        isReady = false;
        try {
            command.execute(bot, botChannel, vcChannel);
        } catch (error){
            console.error(error);
        }
        doStuffAsync();
    }
});

Seemed to work for now, as 10s is a long enough time for bot to leave discord properly without causing timeout. I'm still open to better suggestions for optimization though!