Implementing a universal timer for tmi.js and discord.js integration

I am currently working on a Discord bot that monitors multiple Twitch chats for commands and executes them on Discord using tmi.js and discord.js. Everything is functioning as expected, but I am facing an issue with implementing a global cooldown on the commands to prevent spamming. Initially, I attempted to add a cooldown timer to each command individually but encountered difficulties in making it work. Therefore, I decided to implement a global cooldown without success. Is there something I am doing incorrectly?

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);
    }
        
});

Answer №1

After doing some research, I found a helpful solution for handling async await functions on Stack Overflow: . With that as my starting point, I made some adjustments to the code:

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();
    }
});

So far, this approach has been effective, particularly with the 10-second delay allowing the bot to exit Discord without any timeouts. I'm still open to suggestions for further optimization!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Express.JS failing to save data to file when using NeDB

Currently, I am developing a bulk import feature for my personal password manager and I have encountered a problem. The issue arises when trying to import an array of passwords using the forEach() method to iterate through each one. After calling the inse ...

Can Angular facilitate the establishment of an Express.js server directly in the browser?

Can an Express.js server be initialized within the browser using Angular? I am interested in executing Node scripts on the Express server via an Angular component. ...

Adding a new object to a mongoDB collection using its unique id

I have a collection named Users where user messages and information are stored. My goal is to add new objects to the existing collection based on their id. When trying to perform this action, I encounter an error 'TypeError: user.insert is not a func ...

The MEAN stack consistently shows an error message of 'Invalid password' whenever a user attempts to log in

I have been working on creating a user login system in node.js with mongoose and MongoDB. Everything works fine when registering new users, but after a few successful logins, an error stating "Invalid password" starts to appear. I would appreciate any assi ...

"Combining AngularJS with Material Design disrupts the functionality of infinite scroll

Issue: Infinite scroll is loading all pages at once instead of waiting for the user to scroll to the page bottom. Environment: AngularJS 1.3.17 Materials Design 0.10.0 Infinite scroll script: https://github.com/sroze/ngInfiniteScroll Demo being used: The ...

Is there a way to enable drag and drop functionality on a dynamically created table using AJAX?

I have been successfully using the TableDnD plugin for drag and drop functionality on table rows. However, I am now facing an issue with dynamically generated tables via AJAX. The code doesn't seem to work as expected when it comes to drag and droppin ...

Creating interactive form fields using React

How can I update nested fields in react forms? First, create a new item using handleAddShareholder. Next, delete an existing item with handleRemoveShareholder. To change details of an item, use handleShareholderNameChange. You can then add a new array ...

What is the process of this script when initiated with an NPM build command?

I have a package.JSON file with the following scripts: "scripts": { "typings": "typings install", "build": "tsc && webpack", "watch": "npm-run-all -p -r -l tsc-watch webpack-watch", "tsc-watch": "tsc -w", "webpack-watch": "web ...

Dual Socket.io connectivity

Here's a simple question I have. I am running a Node.js server with the following code snippet: io.on('connection', function (socket) { console.log('connection'); }); On my webpage, I have this line of code: var socket = io(); ...

What is the best way to title an uploaded chunk with HTML5?

Here is the script I am working with: function upload_by_chunks() { var chunk_size = 1048576; // 1MB function slice(start, end) { if (file.slice) { return file.slice(start, end); } else if (file.webkitSlice) { ...

Encountering a value accessor error when attempting to test a simple form in Angular 4 and Ionic 3

My ionic form is quite simple: <ion-header> <ion-navbar> <ion-title>Foo</ion-title> </ion-navbar> </ion-header> <ion-content padding> <form [formGroup]="fooForm"> <ion-item> ...

Using a URL in an AJAX request

Before redirecting to another page, I am storing data from a textbox. When the user clicks the back button on the page load function in JavaScript, I retrieve the data from the textbox using: var pageval = $('#grid') .load('/Dealer/AllClai ...

The issue in Vue JS arises when trying to access JSON key values from an object array using v-for

I am currently working on parsing a list of objects found within a JSON payload into a table utilizing Vue.js. My goal is to extract the keys from the initial object in the array and use them as headings for the table. While the code I have in place succe ...

Replace the image source with a list of images

I am looking to create a dynamic image list using either an array or an HTML list. When I hover over an image, it should change one by one with a fade or slide effect, and revert back to the default images when I hover out. Question 1: What type of list s ...

Struggling to construct a binary tree as my descendants are not arranged in the right sequence

I am currently working on building a binary tree using PHP, MySQL, and a jQuery plugin developed by Frank-Mich. Here is the progress I have made so far... DATABASE STRUCTURE CREATE TABLE IF NOT EXISTS `members` ( `id` int(11) NOT NULL AUTO_INCREMENT, ...

Uploading data using NodeJS and EJS

Currently, I am utilizing NodeJS/Express and EJS to develop a form for an API route. However, when attempting a POST request and accessing req.body.password & req.body.confirm, I consistently receive "undefined" as the response. index.js import http from ...

Cached images do not trigger the OnLoad event

Is there a way to monitor the load event of my images? Here's my current approach. export const Picture: FC<PictureProps> = ({ src, imgCls, picCls, lazy, alt: initialAlt, onLoad, onClick, style }) => { const alt = useMemo(() => initial ...

Encountering an error when creating LevelDB with NodeJS

Attempting to access a database using the following code: const LevelUP = require('levelup'); const LevelDown = require('leveldown'); const path = require('os').homedir() + '/keys.db'; const db = LevelUP(LevelDow ...

Tips for triggering several functions with a single onClick event in React?

I am currently working on a React Project where I have defined several functions to set conditions for rendering components on the page. However, I now need to be able to call all these functions again within the components when a button is clicked, in ord ...

Employing AJAX, execute a synchronous function asynchronously (Javascript)

Here's a code snippet for the sync function. I've been calling it inside an Ajax, but apparently it's deprecated because it's synchronous. Is there any way to make it run as if it were asynchronous? Or is there a way to convert it into ...