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

@@ -42,6 +42,7 @@ const EMPTY_DRAFT = {
components: null as MessageComponentsV2 | null,
responseType: 'TEXT' as TagResponseType,
triggerWord: '',
cooldownSeconds: 15,
allowedRoleIds: [] as string[],
allowedChannelIds: [] as string[]
};
@@ -56,6 +57,7 @@ export function TagsManager({ guildId, initialTags }: TagsManagerProps) {
const [tags, setTags] = useState<LocalTag[]>(
initialTags.map((tag, index) => ({
...tag,
cooldownSeconds: tag.cooldownSeconds ?? 15,
embed: tag.embed ?? null,
components: tag.components ?? null,
clientKey: tag.id ?? `existing-${index}`
@@ -100,6 +102,7 @@ export function TagsManager({ guildId, initialTags }: TagsManagerProps) {
components: validated.components,
responseType: draft.responseType,
triggerWord: draft.triggerWord.trim() || null,
cooldownSeconds: draft.cooldownSeconds,
allowedRoleIds: draft.allowedRoleIds,
allowedChannelIds: draft.allowedChannelIds
})
@@ -142,6 +145,7 @@ export function TagsManager({ guildId, initialTags }: TagsManagerProps) {
components: validated.components,
responseType: tag.responseType,
triggerWord: tag.triggerWord,
cooldownSeconds: tag.cooldownSeconds,
allowedRoleIds: tag.allowedRoleIds,
allowedChannelIds: tag.allowedChannelIds
})
@@ -255,6 +259,22 @@ export function TagsManager({ guildId, initialTags }: TagsManagerProps) {
<Label>{t('modulePages.tags.triggerWord')}</Label>
<Input value={draft.triggerWord} onChange={(event) => setDraft((prev) => ({ ...prev, triggerWord: event.target.value }))} placeholder={t('common.optional')} />
</div>
<div className="space-y-2">
<Label>{t('modulePages.tags.cooldownSeconds')}</Label>
<Input
type="number"
min={0}
max={3600}
value={draft.cooldownSeconds}
onChange={(event) =>
setDraft((prev) => ({
...prev,
cooldownSeconds: Math.min(3600, Math.max(0, Number(event.target.value) || 0))
}))
}
/>
<p className="text-xs text-muted-foreground">{t('modulePages.tags.cooldownHint')}</p>
</div>
</div>
{renderResponseEditor(
draft.responseType,
@@ -325,6 +345,28 @@ export function TagsManager({ guildId, initialTags }: TagsManagerProps) {
<Label>{t('modulePages.tags.triggerWord')}</Label>
<Input value={tag.triggerWord ?? ''} onChange={(event) => setTags((prev) => prev.map((entry) => (entry.clientKey === tag.clientKey ? { ...entry, triggerWord: event.target.value || null } : entry)))} />
</div>
<div className="space-y-2">
<Label>{t('modulePages.tags.cooldownSeconds')}</Label>
<Input
type="number"
min={0}
max={3600}
value={tag.cooldownSeconds}
onChange={(event) =>
setTags((prev) =>
prev.map((entry) =>
entry.clientKey === tag.clientKey
? {
...entry,
cooldownSeconds: Math.min(3600, Math.max(0, Number(event.target.value) || 0))
}
: entry
)
)
}
/>
<p className="text-xs text-muted-foreground">{t('modulePages.tags.cooldownHint')}</p>
</div>
</div>
{renderResponseEditor(
tag.responseType,

View File

@@ -724,6 +724,13 @@ export const SETTINGS_SEARCH_FIELDS: SearchIndexEntry[] = [
href: 'tags',
hash: 'field-tags-list'
},
{
id: 'setting-tags-cooldown',
kind: 'setting',
labelKey: 'modulePages.tags.cooldownSeconds',
href: 'tags',
hash: 'field-tags-create'
},
// Starboard
{
id: 'setting-starboard-enabled',

View File

@@ -1,5 +1,6 @@
import type { StatsConfigDashboard, StatsConfigDashboardPatch } from '@nexumi/shared';
import { prisma } from '../prisma';
import { addJobAndAwait, getStatsQueue, getStatsQueueEvents } from '../queues';
async function ensureStatsConfig(guildId: string) {
await prisma.guild.upsert({ where: { id: guildId }, update: {}, create: { id: guildId } });
@@ -18,6 +19,46 @@ function toDashboard(config: Awaited<ReturnType<typeof ensureStatsConfig>>): Sta
};
}
/**
* Dashboard has no discord.js Client, so channel renames are delegated to the bot
* via the `stats` BullMQ queue (`statsRefreshGuild`).
*/
async function enqueueStatsRefresh(guildId: string): Promise<void> {
const { confirmed } = await addJobAndAwait(
getStatsQueue(),
getStatsQueueEvents(),
'statsRefreshGuild',
{ guildId },
{
jobId: `stats-refresh-${guildId}-${Date.now()}`,
removeOnComplete: true,
removeOnFail: 25
},
30_000
);
if (!confirmed) {
console.warn('[stats] guild refresh not confirmed in time', { guildId });
}
}
async function maybeRefreshStatsChannels(guildId: string): Promise<void> {
const config = await prisma.statsConfig.findUnique({ where: { guildId } });
if (
!config?.enabled ||
(!config.membersChannelId && !config.onlineChannelId && !config.boostsChannelId)
) {
return;
}
// Config save must succeed even if Discord rename fails (permissions / bot down).
try {
await enqueueStatsRefresh(guildId);
} catch (error) {
console.warn('[stats] refresh after dashboard save failed', { guildId, error });
}
}
export async function getStatsDashboard(guildId: string): Promise<StatsConfigDashboard> {
const config = await ensureStatsConfig(guildId);
return toDashboard(config);
@@ -45,5 +86,7 @@ export async function updateStatsDashboard(
: {})
}
});
await maybeRefreshStatsChannels(guildId);
return toDashboard(updated);
}

View File

@@ -42,6 +42,7 @@ function toDashboard(tag: Tag): TagDashboard {
components: parseComponents(tag.components),
responseType: tag.responseType as TagDashboard['responseType'],
triggerWord: tag.triggerWord,
cooldownSeconds: tag.cooldownSeconds,
allowedRoleIds: tag.allowedRoleIds,
allowedChannelIds: tag.allowedChannelIds
};
@@ -83,6 +84,7 @@ export async function createTag(
: (input.components as Prisma.InputJsonValue),
responseType: input.responseType,
triggerWord: input.triggerWord ?? null,
cooldownSeconds: input.cooldownSeconds ?? 15,
allowedRoleIds: input.allowedRoleIds,
allowedChannelIds: input.allowedChannelIds,
createdById
@@ -124,6 +126,7 @@ export async function updateTag(
: {}),
...(patch.responseType !== undefined ? { responseType: patch.responseType } : {}),
...(patch.triggerWord !== undefined ? { triggerWord: patch.triggerWord } : {}),
...(patch.cooldownSeconds !== undefined ? { cooldownSeconds: patch.cooldownSeconds } : {}),
...(patch.allowedRoleIds !== undefined ? { allowedRoleIds: patch.allowedRoleIds } : {}),
...(patch.allowedChannelIds !== undefined ? { allowedChannelIds: patch.allowedChannelIds } : {})
}

View File

@@ -24,6 +24,7 @@ export const automodQueueName = 'automod';
export const presenceQueueName = 'presence';
export const selfrolesQueueName = 'selfroles';
export const ticketsQueueName = 'tickets';
export const statsQueueName = 'stats';
const globalForQueues = globalThis as unknown as {
__nexumiGiveawayQueue?: Queue;
@@ -36,6 +37,7 @@ const globalForQueues = globalThis as unknown as {
__nexumiPresenceQueue?: Queue;
__nexumiSelfrolesQueue?: Queue;
__nexumiTicketsQueue?: Queue;
__nexumiStatsQueue?: Queue;
__nexumiGiveawayQueueEvents?: QueueEvents;
__nexumiGuildBackupQueueEvents?: QueueEvents;
__nexumiSuggestionsQueueEvents?: QueueEvents;
@@ -43,6 +45,7 @@ const globalForQueues = globalThis as unknown as {
__nexumiSelfrolesQueueEvents?: QueueEvents;
__nexumiVerificationQueueEvents?: QueueEvents;
__nexumiTicketsQueueEvents?: QueueEvents;
__nexumiStatsQueueEvents?: QueueEvents;
};
function queueConnection() {
@@ -124,6 +127,13 @@ export function getTicketsQueue(): Queue {
return globalForQueues.__nexumiTicketsQueue;
}
export function getStatsQueue(): Queue {
globalForQueues.__nexumiStatsQueue ??= new Queue(statsQueueName, {
connection: queueConnection()
});
return globalForQueues.__nexumiStatsQueue;
}
/**
* QueueEvents instances are only needed for jobs where the dashboard needs
* to wait for the bot to finish (e.g. ending a giveaway so the winners list
@@ -178,6 +188,13 @@ export function getTicketsQueueEvents(): QueueEvents {
return globalForQueues.__nexumiTicketsQueueEvents;
}
export function getStatsQueueEvents(): QueueEvents {
globalForQueues.__nexumiStatsQueueEvents ??= new QueueEvents(statsQueueName, {
connection: queueEventsConnection()
});
return globalForQueues.__nexumiStatsQueueEvents;
}
const DEFAULT_WAIT_TIMEOUT_MS = 15_000;
/**

View File

@@ -820,6 +820,8 @@
"COMPONENTS_V2": "Components V2"
},
"triggerWord": "Auslöse-Wort (optional)",
"cooldownSeconds": "Cooldown (Sekunden)",
"cooldownHint": "Mindestabstand zwischen Auto-Antworten im selben Kanal. 0 = kein Cooldown. Standard: 15.",
"content": "Inhalt",
"embed": "Embed",
"components": "Components-V2-Layout",
@@ -899,13 +901,13 @@
},
"stats": {
"title": "Server-Statistiken",
"description": "Automatisch aktualisierte Voice-Kanäle mit Live-Serverstatistiken.",
"description": "Voice-Kanäle mit Live-Werten. Nach dem Speichern (Modul aktiviert) werden die Namen sofort aktualisiert, danach alle 10 Minuten. Der Bot braucht „Kanäle verwalten“.",
"enabledLabel": "Server-Statistiken aktiviert",
"membersChannelId": "Mitglieder-Kanal-ID",
"membersChannelId": "Mitglieder-Kanal",
"membersTemplate": "Mitglieder-Vorlage",
"onlineChannelId": "Online-Kanal-ID",
"onlineChannelId": "Online-Kanal",
"onlineTemplate": "Online-Vorlage",
"boostsChannelId": "Boosts-Kanal-ID",
"boostsChannelId": "Boosts-Kanal",
"boostsTemplate": "Boosts-Vorlage",
"templateHint": "Nutze {count} als Platzhalter für den Live-Wert."
},

View File

@@ -820,6 +820,8 @@
"COMPONENTS_V2": "Components V2"
},
"triggerWord": "Trigger word (optional)",
"cooldownSeconds": "Cooldown (seconds)",
"cooldownHint": "Minimum time between auto-replies in the same channel. 0 = no cooldown. Default: 15.",
"content": "Content",
"embed": "Embed",
"components": "Components V2 layout",
@@ -899,13 +901,13 @@
},
"stats": {
"title": "Server Stats",
"description": "Auto-updating voice channels showing live server statistics.",
"description": "Voice channels with live values. After saving (module enabled) names update immediately, then every 10 minutes. The bot needs Manage Channels.",
"enabledLabel": "Server stats enabled",
"membersChannelId": "Members channel ID",
"membersChannelId": "Members channel",
"membersTemplate": "Members template",
"onlineChannelId": "Online channel ID",
"onlineChannelId": "Online channel",
"onlineTemplate": "Online template",
"boostsChannelId": "Boosts channel ID",
"boostsChannelId": "Boosts channel",
"boostsTemplate": "Boosts template",
"templateHint": "Use {count} as a placeholder for the live value."
},