Skip to content

Commit

Permalink
add command cooldown (static 60s)
Browse files Browse the repository at this point in the history
  • Loading branch information
skarab42 committed Nov 30, 2020
1 parent ad3a4db commit d25d463
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 4 deletions.
4 changes: 4 additions & 0 deletions app/server/db/Models/Command.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ const Command = sequelize.define("Command", {
type: DataTypes.STRING,
allowNull: true,
},
cooldown: {
type: DataTypes.INTEGER,
defaultValue: 60,
},
enabled: {
type: DataTypes.BOOLEAN,
defaultValue: true,
Expand Down
5 changes: 5 additions & 0 deletions app/server/libs/twitch/api/getCommandByName.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
const Command = require("../../../db/Models/Command");

module.exports = async function getCommandByName(name) {
return await Command.findOne({ where: { name } });
};
23 changes: 19 additions & 4 deletions app/server/libs/twitch/chat/onCommand.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,28 @@
const getCommandNames = require("../api/getCommandNames");
const getCommandByName = require("../api/getCommandByName");
const pushActions = require("../pushActions");
const { _ } = require("../../i18next");
const ms = require("ms");

module.exports = async function onCommand({ command, nick, message }) {
const commands = await getCommandNames();
const cooldowns = {};

if (!commands.includes(command.name)) {
module.exports = async function onCommand({ channel, command, nick, message }) {
const commandEntry = await getCommandByName(command.name);
const now = Date.now();

if (!commandEntry) {
throw new Error(`${_("twitch.command-not-found")} ${command.name}`);
}

const lastCall = cooldowns[command.name] || 0;
const cooldown = commandEntry.cooldown * 1000;
const elapsedTime = now - lastCall;

if (elapsedTime < cooldown) {
const rest = cooldown - elapsedTime;
this.say(channel, `Cooldown for ${command.name} -> ~${ms(rest)}`);
return;
}

cooldowns[command.name] = now;
pushActions("onCommand", { user: nick, message, command });
};

0 comments on commit d25d463

Please sign in to comment.