Implement Owner Panel features and maintenance mode handling

- Introduced the Owner Panel with new routes and UI components for managing guilds, user blacklists, feature flags, and bot presence.
- Added maintenance mode functionality to prevent non-owner users from executing commands during maintenance periods.
- Enhanced localization with new keys for Owner Panel features in both English and German.
- Updated job processing to include a presence refresh job, ensuring the bot's status is regularly updated.
- Improved environment configuration to support owner user IDs for access control.
This commit is contained in:
smueller
2026-07-22 16:10:30 +02:00
parent bcbfa07697
commit 8a8aefb4fb
42 changed files with 2385 additions and 50 deletions

View File

@@ -8,6 +8,7 @@ import { t } from '@nexumi/shared';
import { env } from './env.js';
import { logger } from './logger.js';
import { getGuildLocale } from './i18n.js';
import { isMaintenanceMode } from './presence.js';
import { moderationCommands } from './modules/moderation/commands.js';
import { automodCommands } from './modules/automod/commands.js';
import { welcomeCommands } from './modules/welcome/commands.js';
@@ -91,8 +92,18 @@ export async function registerCommands() {
}
export async function routeCommand(interaction: ChatInputCommandInteraction, context: BotContext) {
const command = map.get(interaction.commandName);
const locale = await getGuildLocale(context.prisma, interaction.guildId);
const maintenance = await isMaintenanceMode(context);
const ownerIds = env.OWNER_USER_IDS ?? [];
if (maintenance.enabled && !ownerIds.includes(interaction.user.id)) {
await interaction.reply({
content: maintenance.message?.trim() || t(locale, 'generic.maintenance'),
ephemeral: true
});
return;
}
const command = map.get(interaction.commandName);
if (!command) {
await interaction.reply({ content: t(locale, 'generic.unknownCommand'), ephemeral: true });
return;

View File

@@ -22,7 +22,21 @@ const EnvSchema = z.object({
HEALTH_PORT: z.coerce.number().int().positive().default(8080),
PUBLIC_BASE_URL: z.string().url().default('http://localhost:8080'),
TWITCH_CLIENT_ID: z.preprocess(emptyToUndefined, z.string().min(1).optional()),
TWITCH_CLIENT_SECRET: z.preprocess(emptyToUndefined, z.string().min(1).optional())
TWITCH_CLIENT_SECRET: z.preprocess(emptyToUndefined, z.string().min(1).optional()),
OWNER_USER_IDS: z.preprocess(
emptyToUndefined,
z
.string()
.optional()
.transform((value) =>
value
? value
.split(',')
.map((id) => id.trim())
.filter((id) => id.length > 0)
: []
)
)
});
export const env = EnvSchema.parse(process.env);

View File

@@ -119,6 +119,12 @@ if (!isShard) {
} catch (error) {
logger.error({ error }, 'Failed to register application commands');
}
try {
const { applyBotPresence } = await import('./presence.js');
await applyBotPresence(context);
} catch (error) {
logger.warn({ error }, 'Failed to apply initial bot presence');
}
});
client.on(Events.MessageCreate, async (message) => {

View File

@@ -20,6 +20,7 @@ import { pollAllFeeds } from './modules/feeds/index.js';
import { sendScheduledMessage } from './modules/scheduler/index.js';
import { runGuildBackupRestoreJob } from './modules/guildbackup/index.js';
import { runSuggestionStatusUpdateJob } from './modules/suggestions/index.js';
import { runPresenceRefreshJob } from './presence.js';
import {
automodQueue,
automodQueueName,
@@ -32,6 +33,8 @@ import {
giveawayQueueName,
guildBackupQueueName,
moderationQueueName,
presenceQueue,
presenceQueueName,
reminderQueueName,
scheduleQueueName,
suggestionsQueueName,
@@ -304,6 +307,20 @@ export function startWorkers(context: BotContext): Worker[] {
logger.error({ jobId: job?.id, error }, 'Suggestion status update job failed');
});
const presenceWorker = new Worker(
presenceQueueName,
async (job) => {
if (job.name !== 'presenceRefresh') {
return;
}
await runPresenceRefreshJob(context);
},
{ connection: redis }
);
presenceWorker.on('failed', (job, error) => {
logger.error({ jobId: job?.id, error }, 'Presence refresh job failed');
});
return [
moderationWorker,
backupWorker,
@@ -317,7 +334,8 @@ export function startWorkers(context: BotContext): Worker[] {
feedsWorker,
scheduleWorker,
guildBackupWorker,
suggestionsWorker
suggestionsWorker,
presenceWorker
];
}
@@ -375,6 +393,16 @@ export async function ensureRecurringJobs(): Promise<void> {
removeOnFail: 20
}
);
await presenceQueue.add(
'presenceRefresh',
{},
{
repeat: { every: 60_000 },
removeOnComplete: 5,
removeOnFail: 5
}
);
}
async function runPgDumpBackup(): Promise<void> {

78
apps/bot/src/presence.ts Normal file
View File

@@ -0,0 +1,78 @@
import { ActivityType } from 'discord.js';
import { PRESENCE_REDIS_KEY, BotPresenceConfigSchema, type BotPresenceConfig } from '@nexumi/shared';
import { redis } from './redis.js';
import { logger } from './logger.js';
import type { BotContext } from './types.js';
const ACTIVITY_TYPE_MAP: Record<BotPresenceConfig['activityType'], ActivityType> = {
Playing: ActivityType.Playing,
Listening: ActivityType.Listening,
Watching: ActivityType.Watching,
Competing: ActivityType.Competing
};
export async function readPresenceConfig(context: BotContext): Promise<BotPresenceConfig> {
const cached = await redis.get(PRESENCE_REDIS_KEY);
if (cached) {
const parsed = BotPresenceConfigSchema.safeParse(JSON.parse(cached));
if (parsed.success) {
return parsed.data;
}
}
const row = await context.prisma.botPresenceConfig.upsert({
where: { id: 'singleton' },
create: { id: 'singleton' },
update: {}
});
const rotating = Array.isArray(row.rotatingMessages)
? row.rotatingMessages.filter((item: unknown): item is string => typeof item === 'string')
: [];
const config = BotPresenceConfigSchema.parse({
status: row.status,
activityType: row.activityType,
activityText: row.activityText,
rotatingMessages: rotating,
maintenanceMode: row.maintenanceMode,
maintenanceMessage: row.maintenanceMessage
});
await redis.set(PRESENCE_REDIS_KEY, JSON.stringify(config));
return config;
}
export async function applyBotPresence(context: BotContext): Promise<void> {
const config = await readPresenceConfig(context);
const messages =
config.rotatingMessages.length > 0 ? config.rotatingMessages : [config.activityText];
const index = Math.floor(Date.now() / 60_000) % messages.length;
const text = messages[index] ?? config.activityText;
await context.client.user?.setPresence({
status: config.status,
activities: [
{
name: text,
type: ACTIVITY_TYPE_MAP[config.activityType]
}
]
});
}
export async function isMaintenanceMode(context: BotContext): Promise<{
enabled: boolean;
message: string | null;
}> {
const config = await readPresenceConfig(context);
return {
enabled: config.maintenanceMode,
message: config.maintenanceMessage
};
}
export async function runPresenceRefreshJob(context: BotContext): Promise<void> {
try {
await applyBotPresence(context);
} catch (error) {
logger.warn({ error }, 'Failed to apply bot presence');
}
}

View File

@@ -27,3 +27,5 @@ export const guildBackupQueueName = 'guild-backups';
export const guildBackupQueue = new Queue(guildBackupQueueName, { connection: redis });
export const suggestionsQueueName = 'suggestions';
export const suggestionsQueue = new Queue(suggestionsQueueName, { connection: redis });
export const presenceQueueName = 'presence';
export const presenceQueue = new Queue(presenceQueueName, { connection: redis });