Skip to content

Commit

Permalink
refactor(utilities): Use relative timestamps (#993)
Browse files Browse the repository at this point in the history
* refactor(utilities): Use relative timestamps

* chore: prettier formatting

* refactor(utilities): use relative timestamp

* refactor: messages

---------

Co-authored-by: Vijay Meena (Samar) <sumarmeena@gmail.com>
  • Loading branch information
ravener and Vijay Meena (Samar) authored Mar 13, 2024
1 parent a2a6220 commit 426361f
Show file tree
Hide file tree
Showing 7 changed files with 50 additions and 33 deletions.
5 changes: 5 additions & 0 deletions .changeset/rare-birds-matter.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@discordx/utilities": minor
---

use relative time in rate limit guard
4 changes: 2 additions & 2 deletions packages/utilities/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -153,14 +153,14 @@ class RateLimitExample {
/**
* Allow 3 command before rate limit of 30 seconds (from last message)
*/
@Slash({ name: "rate_limit_3" })
@Slash({ name: "rate_limit_2" })
@Guard(
RateLimit(TIME_UNIT.seconds, 30, {
message: "Please wait `30` seconds!",
rateValue: 3,
}),
)
rateLimit3(interaction: CommandInteraction): void {
rateLimit2(interaction: CommandInteraction): void {
interaction.reply("It worked!");
}

Expand Down
12 changes: 6 additions & 6 deletions packages/utilities/examples/guards/commands/PermissionGuards.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ export class PermissionGuards {
* @param interaction
*/
@Slash({
description: "permission_ban_members",
name: "permission_ban_members",
description: "permission_ban_members_1",
name: "permission_ban_members_1",
})
@Guard(PermissionGuard(["BanMembers"]))
banMembers1(interaction: CommandInteraction): void {
Expand All @@ -26,8 +26,8 @@ export class PermissionGuards {
* @param interaction
*/
@Slash({
description: "permission_ban_members",
name: "permission_ban_members",
description: "permission_ban_members_2",
name: "permission_ban_members_2",
})
@Guard(
PermissionGuard(["BanMembers"], {
Expand All @@ -45,8 +45,8 @@ export class PermissionGuards {
* @param interaction
*/
@Slash({
description: "permission_ban_members",
name: "permission_ban_members",
description: "permission_ban_members_3",
name: "permission_ban_members_3",
})
@Guard(
PermissionGuard(PermissionGuards.resolvePermission, {
Expand Down
7 changes: 3 additions & 4 deletions packages/utilities/examples/guards/commands/RateLimit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,8 @@ export class RateLimitExample {
*/
@Slash({ description: "rate_limit_4", name: "rate_limit_4" })
@Guard(
RateLimit(TIME_UNIT.seconds, 30, {
message:
"Slow Down, please try at {until}, if you do not try at {until} then this command will not work",
RateLimit(TIME_UNIT.minutes, 5, {
message: "Slow Down, please try in {time}",
}),
)
rateLimit4(interaction: CommandInteraction): void {
Expand Down Expand Up @@ -86,7 +85,7 @@ export class RateLimitExample {
return Promise.resolve(
`${
interaction.commandName
} will be available again at {until}, this is in ${Math.round(
} will be available again in {time}, this is in ${Math.round(
timeLeft / 1000,
)} seconds`,
);
Expand Down
45 changes: 29 additions & 16 deletions packages/utilities/src/guards/Rate Limiter/RateLimit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import type {
import type { GuardFunction } from "discordx";
import { SimpleCommandMessage } from "discordx";

import { dayjs } from "../../useful/time-format.js";
import type { RateLimitOption } from "./index.js";
import { TIME_UNIT, TimedSet } from "./index.js";
import { TimeOutEntry } from "./logic/index.js";
Expand All @@ -23,15 +24,15 @@ export function RateLimit<T extends CommandInteraction | SimpleCommandMessage>(
timeout: TIME_UNIT,
value: number,
options: RateLimitOption<T> = {
ephemeral: false,
message: "message being rate limited!, please try again at {until}",
ephemeral: true,
message: "message being rate limited!, please try again in {time}",
rateValue: 1,
},
): GuardFunction<T> {
const rateValue = options?.rateValue ?? 1;
const rateMessage =
options?.message ??
"message being rate limited!, please try again at {until}";
"message being rate limited!, please try again in {time}";

function convertToMillisecond(timeValue: number, unit: TIME_UNIT): number {
switch (unit) {
Expand Down Expand Up @@ -96,7 +97,7 @@ export function RateLimit<T extends CommandInteraction | SimpleCommandMessage>(
if (arg instanceof SimpleCommandMessage) {
await arg?.message.reply(msg);
} else {
return replyOrFollowUp(arg, msg, options?.ephemeral ?? false);
return replyOrFollowUp(arg, msg, options?.ephemeral ?? true);
}
}

Expand All @@ -119,23 +120,35 @@ export function RateLimit<T extends CommandInteraction | SimpleCommandMessage>(
let fromArray = getFromArray(memberId, guildId);
if (fromArray) {
fromArray.incrementCallCount();
const timeLeft = getTimeLeft(fromArray);
const whenWillExecute = Date.now() + timeLeft;
if (fromArray.hasLimitReached()) {
const messageString =
/**
* Get time left
*/
const timeLeft = getTimeLeft(fromArray);

/**
* Get message string
*/
let messageString =
typeof rateMessage === "function"
? await rateMessage(arg, timeLeft)
: rateMessage;

if (messageString.includes("{until}")) {
return post(
arg,
messageString.replaceAll(
"{until}",
`<t:${Math.round(whenWillExecute / 1000)}:T>`,
),
);
}
/**
* Get static relative time text
*/
const timeText = dayjs().add(timeLeft, "milliseconds").fromNow(true);

/**
* Format placeholders in message
*/
["{until}", "{time}"].forEach((text) => {
messageString = messageString.replaceAll(text, timeText);
});

/**
* Send message and terminate execution
*/
return post(arg, messageString);
}

Expand Down
4 changes: 2 additions & 2 deletions packages/utilities/src/guards/Rate Limiter/types/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ export type RateLimitOption<
ephemeral?: boolean;
/**
* the message to post when a command is called when the
* user is in rate limit, defaults = "message being rate limited!, please try again at {until}".
* use the placeholder {until} in your string to get the time you can next call it `<t:epoch:T>`
* user is in rate limit, defaults = "message being rate limited!, please try again at {time}".
* use the placeholder {time} in your string to get the time you can next call it `<t:epoch:T>`
* If a function is supplied, it will pass both the interaction and how many milliseconds are left until the rate limit is over
*/
message?: ((interaction: T, timeLeft: number) => Awaitable<string>) | string;
Expand Down
6 changes: 3 additions & 3 deletions packages/utilities/src/useful/time-format.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import myDayJS from "dayjs";
import customParseFormat from "dayjs/plugin/customParseFormat";
import objectSupport from "dayjs/plugin/objectSupport";
import relativeTime from "dayjs/plugin/relativeTime";
import customParseFormat from "dayjs/plugin/customParseFormat.js";
import objectSupport from "dayjs/plugin/objectSupport.js";
import relativeTime from "dayjs/plugin/relativeTime.js";

/**
* Extend dayjs with relativeTime plugin
Expand Down

0 comments on commit 426361f

Please sign in to comment.