Enhance tag management with cooldown feature and related updates

- Added a `cooldownSeconds` field to the `Tag` model, allowing for customizable cooldown periods between tag responses.
- Updated tag command handling to incorporate cooldown logic, preventing spam and improving user experience.
- Enhanced the WebUI to support cooldown configuration for tags, including input validation and localization for cooldown messages.
- Refactored tag-related service functions to manage cooldowns effectively, ensuring accurate tracking and enforcement.
- Improved localization for new cooldown-related messages in both English and German.
This commit is contained in:
TheOnlyMace
2026-07-25 16:50:46 +02:00
parent 5f932f5d63
commit bc4fae5415
21 changed files with 318 additions and 39 deletions

View File

@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "Tag" ADD COLUMN "cooldownSeconds" INTEGER NOT NULL DEFAULT 15;

View File

@@ -584,21 +584,22 @@ model SelfRolePanel {
}
model Tag {
id String @id @default(cuid())
guildId String
name String
content String?
embed Json?
components Json?
responseType String @default("TEXT")
triggerWord String?
allowedRoleIds String[] @default([])
id String @id @default(cuid())
guildId String
name String
content String?
embed Json?
components Json?
responseType String @default("TEXT")
triggerWord String?
cooldownSeconds Int @default(15)
allowedRoleIds String[] @default([])
allowedChannelIds String[] @default([])
createdById String
useCount Int @default(0)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
guild Guild @relation(fields: [guildId], references: [id], onDelete: Cascade)
createdById String
useCount Int @default(0)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
guild Guild @relation(fields: [guildId], references: [id], onDelete: Cascade)
@@unique([guildId, name])
@@index([guildId])

View File

@@ -7,8 +7,8 @@ import { invitesCommandData, statsCommandData } from './command-definitions.js';
import { getInviteLeaderboard, getInviteStatsForUser } from './invites.js';
import {
getStatsConfig,
refreshGuildStatsChannels,
StatsSetupSchema,
updateStatsChannels,
upsertStatsConfig
} from './service.js';
@@ -47,7 +47,7 @@ const statsCommand: SlashCommand = {
}
await upsertStatsConfig(context.prisma, guildId, parsed.data);
await updateStatsChannels(context);
await refreshGuildStatsChannels(context, guildId);
await interaction.reply({ content: t(locale, 'stats.setup.done'), ephemeral: true });
return;
@@ -64,7 +64,7 @@ const statsCommand: SlashCommand = {
return;
}
await updateStatsChannels(context);
await refreshGuildStatsChannels(context, guildId);
await interaction.reply({ content: t(locale, 'stats.refresh.done'), ephemeral: true });
}
}

View File

@@ -4,6 +4,9 @@ export {
ensureStatsRecurringJobs,
startStatsWorker,
updateStatsChannels,
refreshGuildStatsChannels,
runStatsGuildRefreshJob,
STATS_REFRESH_CRON,
STATS_REFRESH_JOB_NAME
STATS_REFRESH_JOB_NAME,
STATS_GUILD_REFRESH_JOB_NAME
} from './service.js';

View File

@@ -21,6 +21,8 @@ export type StatsSetupInput = z.infer<typeof StatsSetupSchema>;
export const STATS_REFRESH_CRON = '*/10 * * * *';
export const STATS_REFRESH_JOB_NAME = 'statsRefresh';
/** One-shot refresh for a single guild (dashboard save / slash refresh). */
export const STATS_GUILD_REFRESH_JOB_NAME = 'statsRefreshGuild';
export async function getStatsConfig(prisma: BotContext['prisma'], guildId: string) {
await ensureGuild(prisma, guildId);
@@ -97,13 +99,17 @@ async function renameStatsChannel(
});
}
async function refreshGuildStatsChannels(context: BotContext, guildId: string): Promise<void> {
export async function refreshGuildStatsChannels(context: BotContext, guildId: string): Promise<void> {
const config = await context.prisma.statsConfig.findUnique({ where: { guildId } });
if (!config?.enabled) {
return;
}
const guild = await context.client.guilds.fetch(guildId).catch(() => null);
// withCounts populates approximatePresenceCount / approximateMemberCount.
// GuildPresences is not privileged for us — presence cache would stay empty.
const guild = await context.client.guilds
.fetch({ guild: guildId, withCounts: true })
.catch(() => null);
if (!guild) {
return;
}
@@ -114,9 +120,7 @@ async function refreshGuildStatsChannels(context: BotContext, guildId: string):
return;
}
await guild.members.fetch().catch(() => undefined);
const memberCount = guild.memberCount;
const memberCount = guild.approximateMemberCount ?? guild.memberCount;
const onlineCount = estimateOnlineCount(guild);
const boostCount = guild.premiumSubscriptionCount ?? 0;
@@ -127,6 +131,13 @@ async function refreshGuildStatsChannels(context: BotContext, guildId: string):
]);
}
export async function runStatsGuildRefreshJob(
context: BotContext,
data: { guildId: string }
): Promise<void> {
await refreshGuildStatsChannels(context, data.guildId);
}
export async function updateStatsChannels(context: BotContext): Promise<void> {
const configs = await context.prisma.statsConfig.findMany({
where: { enabled: true }
@@ -159,6 +170,15 @@ export function startStatsWorker(context: BotContext): Worker {
async (job) => {
if (job.name === STATS_REFRESH_JOB_NAME) {
await updateStatsChannels(context);
return;
}
if (job.name === STATS_GUILD_REFRESH_JOB_NAME) {
const guildId = typeof job.data?.guildId === 'string' ? job.data.guildId : null;
if (!guildId) {
logger.warn({ jobId: job.id }, 'statsRefreshGuild missing guildId');
return;
}
await runStatsGuildRefreshJob(context, { guildId });
}
},
{ connection: redis }

View File

@@ -172,6 +172,9 @@ const tagCommand: SlashCommand = {
tag.triggerWord
? tf(locale, 'tag.info.trigger', { word: tag.triggerWord })
: t(locale, 'tag.info.noTrigger'),
tag.cooldownSeconds > 0
? tf(locale, 'tag.info.cooldown', { seconds: tag.cooldownSeconds })
: t(locale, 'tag.info.noCooldown'),
tag.allowedRoleIds.length > 0
? tf(locale, 'tag.info.roles', { roles: tag.allowedRoleIds.map((id) => `<@&${id}>`).join(', ') })
: t(locale, 'tag.info.allRoles'),
@@ -189,8 +192,12 @@ const tagCommand: SlashCommand = {
}
} catch (error) {
if (error instanceof TagError) {
const content =
error.code === 'cooldown' && error.retryAfterSeconds !== undefined
? tf(locale, 'tag.error.cooldown', { seconds: error.retryAfterSeconds })
: t(locale, `tag.error.${error.code}`);
await interaction.reply({
content: t(locale, `tag.error.${error.code}`),
content,
ephemeral: true
});
return;

View File

@@ -4,8 +4,10 @@ import type { BotContext } from '../../types.js';
import { getGuildLocale } from '../../i18n.js';
import { logger } from '../../logger.js';
import {
applyTagCooldown,
buildTagReply,
findTriggeredTag,
getTagCooldownRemaining,
memberCanUseTag,
TagError
} from './service.js';
@@ -31,6 +33,18 @@ export function registerTagEvents(client: Client, context: BotContext): void {
return;
}
// Channel-scoped cooldown: silent skip to avoid spam replies.
if (tag.cooldownSeconds > 0) {
const remaining = await getTagCooldownRemaining(
message.guild.id,
tag.id,
message.channel.id
);
if (remaining > 0) {
return;
}
}
await context.prisma.tag.update({
where: { id: tag.id },
data: { useCount: { increment: 1 } }
@@ -38,6 +52,7 @@ export function registerTagEvents(client: Client, context: BotContext): void {
const payload = buildTagReply(tag, member, message.guild, '');
await message.reply(payload);
await applyTagCooldown(message.guild.id, tag.id, message.channel.id, tag.cooldownSeconds);
} catch (error) {
if (error instanceof TagError) {
const locale = await getGuildLocale(context.prisma, message.guild?.id ?? null);

View File

@@ -14,15 +14,44 @@ import type { Tag } from '@prisma/client';
import { ensureGuild } from '../../guild.js';
import { buildEmbedFromPayload } from '../../lib/embed-payload.js';
import { buildComponentsV2Payload } from '../../lib/components-v2-payload.js';
import { redis } from '../../redis.js';
import type { BotContext } from '../../types.js';
import { assertPremiumLimit, PremiumLimitError } from '../../premium.js';
import { matchesTriggerWord, tagCooldownKey } from './tag-helpers.js';
export { matchesTriggerWord, tagCooldownKey } from './tag-helpers.js';
export class TagError extends Error {
constructor(public readonly code: string) {
constructor(
public readonly code: string,
public readonly retryAfterSeconds?: number
) {
super(code);
}
}
/** Returns remaining cooldown seconds, or 0 if ready. */
export async function getTagCooldownRemaining(
guildId: string,
tagId: string,
scopeId: string
): Promise<number> {
const ttl = await redis.ttl(tagCooldownKey(guildId, tagId, scopeId));
return ttl > 0 ? ttl : 0;
}
export async function applyTagCooldown(
guildId: string,
tagId: string,
scopeId: string,
cooldownSeconds: number
): Promise<void> {
if (cooldownSeconds <= 0) {
return;
}
await redis.set(tagCooldownKey(guildId, tagId, scopeId), '1', 'EX', cooldownSeconds);
}
export function normalizeTagName(name: string): string {
return name.trim().toLowerCase();
}
@@ -147,6 +176,7 @@ export async function createTag(
embed?: WelcomeEmbed | null;
components?: MessageComponentsV2 | null;
triggerWord?: string | null;
cooldownSeconds?: number;
allowedRoleIds?: string[];
allowedChannelIds?: string[];
createdById: string;
@@ -190,6 +220,7 @@ export async function createTag(
embed: params.embed ?? undefined,
components: params.components ?? undefined,
triggerWord: params.triggerWord?.trim() || null,
cooldownSeconds: params.cooldownSeconds ?? 15,
allowedRoleIds: params.allowedRoleIds ?? [],
allowedChannelIds: params.allowedChannelIds ?? [],
createdById: params.createdById
@@ -208,6 +239,7 @@ export async function updateTag(
embed?: WelcomeEmbed | null;
components?: MessageComponentsV2 | null;
triggerWord?: string | null;
cooldownSeconds?: number;
allowedRoleIds?: string[];
allowedChannelIds?: string[];
}
@@ -255,6 +287,8 @@ export async function updateTag(
components: components ?? undefined,
triggerWord:
updates.triggerWord !== undefined ? updates.triggerWord?.trim() || null : existing.triggerWord,
cooldownSeconds:
updates.cooldownSeconds !== undefined ? updates.cooldownSeconds : existing.cooldownSeconds,
allowedRoleIds: updates.allowedRoleIds ?? existing.allowedRoleIds,
allowedChannelIds: updates.allowedChannelIds ?? existing.allowedChannelIds
}
@@ -294,18 +328,22 @@ export async function executeTag(
throw new TagError('not_allowed');
}
const scopeId = member?.id ?? channelId;
if (tag.cooldownSeconds > 0) {
const remaining = await getTagCooldownRemaining(guildId, tag.id, scopeId);
if (remaining > 0) {
throw new TagError('cooldown', remaining);
}
}
await context.prisma.tag.update({
where: { id: tag.id },
data: { useCount: { increment: 1 } }
});
return buildTagReply(tag, member, guild, args);
}
await applyTagCooldown(guildId, tag.id, scopeId, tag.cooldownSeconds);
export function matchesTriggerWord(content: string, triggerWord: string): boolean {
const escaped = triggerWord.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const pattern = new RegExp(`\\b${escaped}\\b`, 'i');
return pattern.test(content);
return buildTagReply(tag, member, guild, args);
}
export async function findTriggeredTag(

View File

@@ -0,0 +1,15 @@
import { describe, expect, it } from 'vitest';
import { matchesTriggerWord, tagCooldownKey } from './tag-helpers.js';
describe('tagCooldownKey', () => {
it('builds a stable redis key', () => {
expect(tagCooldownKey('g1', 't1', 'c1')).toBe('tag:cooldown:g1:t1:c1');
});
});
describe('matchesTriggerWord', () => {
it('matches whole words case-insensitively', () => {
expect(matchesTriggerWord('Hello world', 'hello')).toBe(true);
expect(matchesTriggerWord('say helloworld', 'hello')).toBe(false);
});
});

View File

@@ -0,0 +1,10 @@
/** Redis key for tag cooldowns (guild + tag + user or channel scope). */
export function tagCooldownKey(guildId: string, tagId: string, scopeId: string): string {
return `tag:cooldown:${guildId}:${tagId}:${scopeId}`;
}
export function matchesTriggerWord(content: string, triggerWord: string): boolean {
const escaped = triggerWord.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const pattern = new RegExp(`\\b${escaped}\\b`, 'i');
return pattern.test(content);
}