UNPKG

@sapphire/framework

Version:

Discord bot framework built for advanced and amazing bots.

76 lines (74 loc) 2.88 kB
import { BucketScope } from "../lib/types/Enums.mjs"; import { Identifiers } from "../lib/errors/Identifiers.mjs"; import { AllFlowsPrecondition } from "../lib/structures/Precondition.mjs"; import { container } from "@sapphire/pieces"; import { TimestampStyles, time } from "discord.js"; import { RateLimitManager } from "@sapphire/ratelimits"; //#region src/preconditions/Cooldown.ts var CorePrecondition = class extends AllFlowsPrecondition { constructor(..._args) { super(..._args); this.buckets = /* @__PURE__ */ new WeakMap(); } messageRun(message, command, context) { const cooldownId = this.getIdFromMessage(message, context); return this.sharedRun(message.author.id, command, context, cooldownId, "message"); } chatInputRun(interaction, command, context) { const cooldownId = this.getIdFromInteraction(interaction, context); return this.sharedRun(interaction.user.id, command, context, cooldownId, "chat input"); } contextMenuRun(interaction, command, context) { const cooldownId = this.getIdFromInteraction(interaction, context); return this.sharedRun(interaction.user.id, command, context, cooldownId, "context menu"); } sharedRun(authorId, command, context, cooldownId, commandType) { if (context.external) return this.ok(); if (!context.delay) return this.ok(); if (context.filteredUsers?.includes(authorId)) return this.ok(); const rateLimit = this.getManager(command, context).acquire(cooldownId); if (rateLimit.limited) { const remaining = rateLimit.remainingTime; const nextAvailable = time(Math.floor(rateLimit.expires / 1e3), TimestampStyles.RelativeTime); return this.error({ identifier: Identifiers.PreconditionCooldown, message: `There is a cooldown in effect for this ${commandType} command. It'll be available ${nextAvailable}.`, context: { remaining } }); } rateLimit.consume(); return this.ok(); } getIdFromMessage(message, context) { switch (context.scope) { case BucketScope.Global: return "global"; case BucketScope.Channel: return message.channelId; case BucketScope.Guild: return message.guildId ?? message.channelId; default: return message.author.id; } } getIdFromInteraction(interaction, context) { switch (context.scope) { case BucketScope.Global: return "global"; case BucketScope.Channel: return interaction.channelId; case BucketScope.Guild: return interaction.guildId ?? interaction.channelId; default: return interaction.user.id; } } getManager(command, context) { let manager = this.buckets.get(command); if (!manager) { manager = new RateLimitManager(context.delay, context.limit); this.buckets.set(command, manager); } return manager; } }; container.stores.loadPiece({ name: "Cooldown", piece: CorePrecondition, store: "preconditions" }); //#endregion export { CorePrecondition }; //# sourceMappingURL=Cooldown.mjs.map