refactor: improve code quality

This commit is contained in:
2026-05-12 15:42:21 +02:00
parent 8abdfc3b2f
commit 528fff3a5b
42 changed files with 1756 additions and 1255 deletions

View File

@@ -1,97 +1,45 @@
import type { Client } from "discord.js";
import { createLogger, logger } from "@lbf-bot/utils";
import type { Client, OmitPartialGroupDMChannel, Message } from "discord.js";
import { logger } from "@lbf-bot/utils";
import { env } from "~/env";
import {
listTrackedPlayers,
getTrackedPlayerUsernames,
addUsernameToHistory,
} from "~/services/tracking";
import { checkForNewQuest, getPlayer } from "~/services/wov";
import { createInfoEmbed } from "~/utils/discord";
import { askForGrinders } from "~/utils/quest";
import { questCheckCron } from "~/quests";
import { trackingCron } from "~/tracking";
import { commands } from "~/commands";
const questsLogger = createLogger({ prefix: "quests" });
const trackingLogger = createLogger({ prefix: "tracking" });
const questCheckCron = async (client: Client) => {
questsLogger.info("Checking for new quest");
const quest = await checkForNewQuest();
if (quest) {
questsLogger.info(`New quest found: '${quest.quest.id}'`);
await askForGrinders(quest, client);
} else {
questsLogger.info("No new quest found");
}
};
const trackingCron = async (client: Client) => {
trackingLogger.info("Checking for tracked players");
const trackedPlayers = await listTrackedPlayers();
trackingLogger.info(`${trackedPlayers.length} players to check`);
for (const playerId of trackedPlayers) {
const player = await getPlayer(playerId);
if (!player) continue;
const usernames = await getTrackedPlayerUsernames(playerId);
if (usernames.includes(player.username)) continue;
await addUsernameToHistory(playerId, player.username);
const chan = client.channels.cache.get(env.DISCORD_TRACKING_CHANNEL);
if (!chan?.isSendable()) {
return logger.fatal("Invalid 'DISCORD_TRACKING_CHANNEL'");
}
const lastUsername = usernames[usernames.length - 1];
await chan.send(
createInfoEmbed(
`### [UPDATE] \`${lastUsername}\` -> \`${player.username}\` [\`${playerId}\`]\n\n**Nouveau pseudo:** \`${player.username}\`\n**Anciens pseudos:**\n${usernames.map((x) => `- \`${x}\``).join("\n")}`,
0x00ea00,
),
);
trackingLogger.info(
`Username changed: ${lastUsername} -> ${player.username} [${playerId}]`,
);
}
};
export const setupBotMode = (client: Client) => {
client.on("clientReady", async (client) => {
const onReady = async (client: Client<true>) => {
logger.info(`Client ready`);
logger.info(`Connected as @${client.user.username}`);
await questCheckCron(client);
setInterval(() => questCheckCron(client), env.WOV_FETCH_INTERVAL);
setInterval(() => void questCheckCron(client), env.WOV_FETCH_INTERVAL);
await trackingCron(client);
setInterval(() => trackingCron(client), env.WOV_TRACKING_INTERVAL);
});
setInterval(() => void trackingCron(client), env.WOV_TRACKING_INTERVAL);
};
client.on("messageCreate", async (message) => {
const onMessage = async (message: OmitPartialGroupDMChannel<Message>, client: Client) => {
if (message.author.bot) return;
if (message.content.startsWith(`<@${client.user!.id}>`)) {
const [command, ...args] = message.content
const [commandName, ...args] = message.content
.replace(`<@${client.user!.id}>`, "")
.trim()
.split(" ");
const commandHandler = commands[command];
if (commandHandler) {
const child = logger.child(
`cmd:${command}${args.length > 0 ? " " : ""}${args.join(" ")}`,
);
const command = commands[commandName];
if (!command) return;
const child = logger.child(`cmd:${commandName}${args.length > 0 ? " " : ""}${args.join(" ")}`);
try {
const start = Date.now();
await commandHandler(message, args);
const end = Date.now();
child.info(`Done in ${(end - start).toFixed(2)}ms`);
const start = Date.now();
await command.handler(message, args);
child.info(`Done in ${(Date.now() - start).toFixed(2)}ms`);
} catch (error: unknown) {
child.error("Failed:", error);
child.error("Failed:", error);
}
}
}
});
};
export const setupBotMode = (client: Client) => {
client.on("clientReady", (client) => { void onReady(client); });
client.on("messageCreate", (message) => { void onMessage(message, client); });
};

View File

@@ -1,36 +1,36 @@
import { logger } from "@lbf-bot/utils";
import type { Client, TextChannel } from "discord.js";
import type { Client } from "discord.js";
import { ChannelType } from "discord.js";
import * as readline from "node:readline";
export const setupUserMode = (client: Client, channelId: string) => {
client.on("clientReady", (client) => {
logger.info(`Client ready`);
logger.info(`Connected as @${client.user.username}`);
client.on("clientReady", (client) => {
logger.info(`Client ready`);
logger.info(`Connected as @${client.user.username}`);
const chan = client.channels.cache.get(channelId);
if (chan?.type !== ChannelType.GuildText) {
console.error("ERROR: invalid channel");
process.exit(1);
}
const chan = client.channels.cache.get(channelId);
if (chan?.type !== ChannelType.GuildText) {
console.error("ERROR: invalid channel");
process.exit(1);
}
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
prompt: `${chan.name} ~ `,
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
prompt: `${chan.name} ~ `,
});
rl.prompt();
rl.on("line", (line) => {
if (line.trim().length > 0) {
void chan.send(line);
}
rl.prompt();
});
rl.on("close", () => {
process.exit(0);
});
});
rl.prompt();
rl.on("line", async (line) => {
if (line.trim().length > 0) {
await (chan as TextChannel).send(line);
}
rl.prompt();
});
rl.on("close", () => {
process.exit(0);
});
});
};