Skip to content

Commit

Permalink
refactor: adopt unified custom logger
Browse files Browse the repository at this point in the history
  • Loading branch information
ryanccn committed May 31, 2023
1 parent c6ed888 commit dac92b7
Show file tree
Hide file tree
Showing 13 changed files with 115 additions and 82 deletions.
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@
"name": "blahaj",
"version": "0.0.1",
"license": "AGPL-3.0-only",
"type": "module",
"private": true,
"scripts": {
"dev": "NODE_ENV=development tsx watch src/index.ts",
"sync-commands": "tsx src/_commands.ts",
"start": "pnpm run sync-commands && NODE_ENV=production tsx src/index.ts",
"start": "NODE_ENV=production tsx src/index.ts",
"lint": "tsc && eslint src"
},
"dependencies": {
Expand All @@ -30,6 +30,7 @@
"@types/node": "^20.2.5",
"@typescript-eslint/eslint-plugin": "^5.59.8",
"@typescript-eslint/parser": "^5.59.8",
"discord-api-types": "^0.37.43",
"eslint": "^8.41.0",
"prettier": "^2.8.8",
"typescript": "^5.0.4"
Expand Down
18 changes: 10 additions & 8 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

24 changes: 15 additions & 9 deletions src/_commands.ts → src/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,13 @@ import {
ContextMenuCommandBuilder,
ApplicationCommandType,
} from "discord.js";

import { REST } from "@discordjs/rest";
import type { RESTGetAPIOAuth2CurrentApplicationResult } from "discord-api-types/v10";

import { defaultLogger } from "~/lib/logger";

import "dotenv/config";
import { green } from "kleur/colors";

export const reuploadCommands = async () => {
const commands = [
Expand Down Expand Up @@ -148,16 +151,19 @@ export const reuploadCommands = async () => {
.map((command) => command.setDMPermission(false))
.map((command) => command.toJSON());

const rest = new REST({ version: "10" }).setToken(process.env.DISCORD_TOKEN!);
const rest = new REST({ version: "10" }).setToken(process.env.DISCORD_TOKEN);

await rest.put(Routes.applicationCommands(process.env.DISCORD_APP!), {
const { id: appId } = (await rest.get(
Routes.oauth2CurrentApplication()
)) as RESTGetAPIOAuth2CurrentApplicationResult;

await rest.put(Routes.applicationCommands(appId), {
body: commands,
});

console.log(green("Successfully registered application commands."));
defaultLogger.success(
`Successfully registered ${commands.length} application command${
commands.length !== 1 ? "s" : ""
}`
);
};

reuploadCommands().catch((e) => {
console.error(e);
process.exit(1);
});
1 change: 0 additions & 1 deletion src/commands/ping.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,5 @@ import type { SlashCommand } from "./_types";
export const pingCommand: SlashCommand = async (i) => {
await i.reply({
content: `Pong! \`${i.client.ws.ping}ms\``,
ephemeral: true,
});
};
2 changes: 1 addition & 1 deletion src/commands/presence.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export const presenceCommand: SlashCommand = async (i) => {
? ActivityType.Competing
: ActivityType.Playing;

i.client.user!.setPresence({
i.client.user.setPresence({
activities: [{ type: parsedType, name: text }],
});

Expand Down
10 changes: 5 additions & 5 deletions src/commands/stableDiffusion.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { EmbedBuilder } from "discord.js";
import { magenta } from "kleur/colors";
import type { SlashCommand } from "./_types";
import { Logger } from "~/lib/logger";

const LOG_PREFIX = magenta("[Stable Diffusion] ");
const logger = new Logger("stable-diffusion");

interface StableDiffusionAPIResponse {
status: "done";
Expand Down Expand Up @@ -69,7 +69,7 @@ export const stableDiffusionCommand: SlashCommand = async (i) => {
return res.json() as Promise<{ call_id: string }>;
});

console.log(LOG_PREFIX + `Dispatched ${callId}`);
logger.info(`Dispatched ${callId}`);

await i.editReply({
embeds: [
Expand All @@ -88,7 +88,7 @@ export const stableDiffusionCommand: SlashCommand = async (i) => {
});

for (let _ = 1; _ <= 60; _++) {
console.log(LOG_PREFIX + `Polling ${callId} (try ${_}/60)`);
logger.info(`Polling ${callId} (try ${_}/60)`);
const statusResp = await fetch(getStatusURL(callId), {
headers: {
Authorization: `Bearer ${process.env.STABLE_DIFFUSION_API_TOKEN}`,
Expand All @@ -101,7 +101,7 @@ export const stableDiffusionCommand: SlashCommand = async (i) => {
} else if (statusResp.status === 200) {
const { data } = (await statusResp.json()) as StableDiffusionAPIResponse;

console.log(LOG_PREFIX + `Received success response from ${callId}`);
logger.info(`Received success response from ${callId}`);

await i.editReply({
embeds: [
Expand Down
6 changes: 4 additions & 2 deletions src/env.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { z, ZodError } from "zod";

import { defaultLogger } from "~/lib/logger";
import { formatZodError } from "~/lib/utils";

const snowflake = z
Expand All @@ -11,7 +13,7 @@ const env = z.object({

DISCORD_APP: z.string().min(1),
DISCORD_TOKEN: z.string().min(1),
REDIS_URL: z.string().url(),
REDIS_URL: z.string().url().optional(),

GOOGLE_CLOUD_PROJECT_ID: z.string().optional(),
GOOGLE_CLOUD_CLIENT_EMAIL: z.string().optional(),
Expand Down Expand Up @@ -50,7 +52,7 @@ export const validateEnv = () => {
env.parse(process.env);
} catch (e: unknown) {
if (e instanceof ZodError) {
console.error(formatZodError(e));
defaultLogger.error(formatZodError(e));
process.exit(1);
} else {
throw e;
Expand Down
24 changes: 8 additions & 16 deletions src/features/chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
type ChatCompletionRequestMessage,
} from "openai";

import { dim, yellow } from "kleur/colors";
import { Logger } from "~/lib/logger";

const SYSTEM_MESSAGE =
"You are a friendly Discord bot named Blåhaj in a small personal Discord guild called Ryanland. Your developer is Ryan Cao (username RyanCaoDev), the owner of the guild, and you were written in Discord.js. You mainly chat casually with members of the community and often make jokes (nicely). You should use very concise language. Due to the conversational nature of Discord, messages NOT BY YOU will be prefixed with the username or nickname of the author, folloed by a colon. You can treat the username as the name of the author. However, you should not not prefix the messages you send with any username whatsoever. You can use the emoji <a:catpat:1102492443523416114> to give members virtual pats when they feel down or ask for pets.";
Expand All @@ -31,6 +31,8 @@ if (process.env.OPENAI_TOKEN) {
openai = new OpenAIApi(configuration);
}

const logger = new Logger("chat");

const unproxiedMessages = new Set<string>();

class UnproxiedMessageError extends Error {
Expand All @@ -41,16 +43,10 @@ export const handleChat = async (message: Message) => {
if (message.interaction) return;

if (!openai) {
console.warn(
yellow(
`No ${dim("`")}OPENAI_TOKEN${dim(
"`"
)} defined, not initializing chatbot`
)
);

logger.warn("No OPENAI_TOKEN defined, not initializing chatbot");
return;
}

if (message.content.startsWith(CHATBOT_ESCAPE_CHAR)) return;

await message.channel.sendTyping();
Expand Down Expand Up @@ -142,14 +138,10 @@ export const handleChat = async (message: Message) => {
clearInterval(typingTimer);

if (e instanceof DiscordAPIError && e.code === 50035) {
console.warn(
yellow(`Unable to reply to message, seems to have been deleted.`)
);
logger.warn("Unable to reply to message, seems to have been deleted.");
} else if (e instanceof UnproxiedMessageError) {
console.warn(
yellow(
`Not replying to ${message.id} because it has been found to be a duplicate`
)
logger.warn(
"Not replying to ${message.id} because it has been found to be a duplicate"
);
} else {
throw e;
Expand Down
3 changes: 2 additions & 1 deletion src/features/logDM.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,11 @@ export const logDM = async (message: Message<boolean>) => {
const logsChannel = await message.client.channels.fetch(
process.env.DM_LOGS_CHANNEL
);
if (!logsChannel || logsChannel.type !== ChannelType.GuildText)
if (!logsChannel || logsChannel.type !== ChannelType.GuildText) {
throw new Error(
`Specified DM logging channel ${process.env.DM_LOGS_CHANNEL} does not exist or is not a text channel!`
);
}

await logsChannel.send({
embeds: [await messageEmbed(message)],
Expand Down
4 changes: 2 additions & 2 deletions src/features/sdMetadata.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { EmbedBuilder, type Message } from "discord.js";
import { parse } from "exifr";
import * as exifr from "exifr";

import { createWriteStream } from "fs";
import { mkdtemp, rm } from "fs/promises";
Expand Down Expand Up @@ -61,7 +61,7 @@ export const parseSDMetadata = async (e: Message<boolean>) => {
createWriteStream(funnyPath)
);

const data = await parse(funnyPath, {
const data = await exifr.parse(funnyPath, {
xmp: true,
});
await rm(funnyPath);
Expand Down
Loading

0 comments on commit dac92b7

Please sign in to comment.