Skip to content

Commit 31ed3e3

Browse files
authored
Merge pull request #27 from hker9527/feat-26
Use logging library
2 parents b60c04e + e8deb2e commit 31ed3e3

File tree

5 files changed

+419
-302
lines changed

5 files changed

+419
-302
lines changed

bun.lockb

344 Bytes
Binary file not shown.

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
"linkifyjs": "^4.0.2",
1515
"node-emoji": "^2.1.0",
1616
"prisma": "^5.1.1",
17+
"tslog": "^4.9.2",
1718
"underscore": "^1.13.6",
1819
"zod": "^3.19.1"
1920
},

src/index.ts

Lines changed: 71 additions & 71 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,20 @@ import type { BaseApplicationCommand } from "@class/ApplicationCommand";
22
import { LocalizableInteractionReplyOptionsAdapter } from "@localizer/InteractionReplyOptions";
33
import assert from "assert-ts";
44
import type { ApplicationCommandType, InteractionReplyOptions, Message, MessageEditOptions, TextChannel } from "discord.js";
5-
import { Client, EmbedBuilder, GatewayIntentBits, Locale, PermissionFlagsBits, PermissionsBitField } from "discord.js";
5+
import { Client, GatewayIntentBits, Locale, PermissionFlagsBits, PermissionsBitField } from "discord.js";
66
import { getName } from "./Localizations";
7-
import { debug, report } from "./Reporting";
87
import { commands } from "./commands";
98
import { modules } from "./modules";
109
import { injectPrototype } from "./prototype";
1110
import { random } from "./utils";
1211
import { LActionRowDataLocalizer } from "@localizer/data/ActionRowData";
1312
import { LocalizableBaseMessageOptionsAdapter } from "@localizer/MessageOptions";
1413
import { PrismaClient } from "@prisma/client";
14+
import { Logger } from "tslog";
15+
16+
const logger = new Logger({
17+
name: "index"
18+
});
1519

1620
const TIMEOUT = 30 * 1000;
1721

@@ -28,29 +32,49 @@ const client = new Client({
2832

2933
const prismaClient = new PrismaClient();
3034

31-
const fetchUserLocale = async (id: string, override?: boolean) => {
32-
const languageItem = await prismaClient.language.findFirst({
33-
where: {
34-
id,
35-
type: "u",
36-
override
37-
}
35+
const fetchUserLocale = async (id: string, override?: boolean): Promise<Locale> => {
36+
const sublogger = logger.getSubLogger({
37+
name: "fetchUserLocale"
3838
});
3939

40-
if (languageItem) {
41-
return languageItem.language as Locale;
40+
try {
41+
const languageItem = await prismaClient.language.findFirst({
42+
where: {
43+
id,
44+
type: "u",
45+
override
46+
}
47+
});
48+
49+
if (languageItem) {
50+
return languageItem.language as Locale;
51+
}
52+
53+
return Locale.EnglishUS;
54+
} catch (e) {
55+
sublogger.error("fetchUserLocale", e);
56+
return Locale.EnglishUS;
4257
}
4358
};
4459

4560
const shouldIgnoreUser = async (id: string) => {
46-
const ignoreItem = await prismaClient.ignore.findFirst({
47-
where: {
48-
id,
49-
type: "u"
50-
}
61+
const sublogger = logger.getSubLogger({
62+
name: "shouldIgnoreUser"
5163
});
5264

53-
return ignoreItem !== null;
65+
try {
66+
const ignoreItem = await prismaClient.ignore.findFirst({
67+
where: {
68+
id,
69+
type: "u"
70+
}
71+
});
72+
73+
return ignoreItem !== null;
74+
} catch (e) {
75+
sublogger.error("shouldIgnoreUser", e);
76+
return false;
77+
}
5478
};
5579

5680
try {
@@ -59,49 +83,25 @@ try {
5983
client.once("ready", async () => {
6084
// Error reporting
6185
const errorChannel = await client.channels.fetch(process.env.error_chid!) as TextChannel;
62-
const error = async (tag: string, e: unknown) => {
63-
const embed = (e instanceof Error ?
64-
new EmbedBuilder({
65-
title: e.name,
66-
fields: [
67-
{
68-
"name": "Tag",
69-
"value": tag
70-
},
71-
{
72-
"name": "Stack",
73-
"value": "```\n" + e.stack?.substring(0, 1000) + "\n```" ?? "(none)"
74-
}
75-
]
76-
}) :
77-
new EmbedBuilder({
78-
title: "Error",
79-
fields: [
80-
{
81-
"name": "Tag",
82-
"value": tag
83-
},
84-
{
85-
"name": "Error",
86-
"value": "```\n" + (e + "").substring(0, 1000) + "\n```" ?? "(none)"
87-
}
88-
]
89-
}));
90-
91-
const obj = {
92-
content: new Date().toISOString(),
93-
embeds: [embed]
94-
};
95-
96-
if (process.env.DEBUG) {
97-
console.error(obj.embeds[0].toJSON().fields![1].value);
98-
} else {
99-
await errorChannel.send(obj);
100-
}
86+
const handleError = async (tag: string, e: unknown) => {
87+
const errorObj = logger.error(tag, e);
88+
// Encode the content into an attachment
89+
const attachment = Buffer.from(JSON.stringify({
90+
time: new Date().toISOString(),
91+
errorObj
92+
}, null, 4));
93+
94+
await errorChannel.send({
95+
content: `Error occurred in \`${tag}\``,
96+
files: [{
97+
name: `${tag}.json`,
98+
attachment
99+
}]
100+
});
101101
};
102102

103103
client.on("error", async (e) => {
104-
await error("client->error", e);
104+
await handleError("client->error", e);
105105
});
106106

107107
const APICommands = commands.map(command => command.toAPI());
@@ -112,19 +112,19 @@ try {
112112
for (const [_, guild] of client.guilds.cache) {
113113
try {
114114
await guild.commands.set(APICommands);
115-
debug("bot.setCommand", `Set command for guild ${guild.name} (${guild.id})`);
115+
logger.debug("bot.setCommand", `Set command for guild ${guild.name} (${guild.id})`);
116116
} catch (e) {
117-
error("bot.setCommand", `Failed to set command for guild ${guild.name} (${guild.id}): ${e}`);
117+
logger.error("bot.setCommand", `Failed to set command for guild ${guild.name} (${guild.id}): ${e}`);
118118
}
119119
}
120120
} else {
121-
report("Setting global commands");
121+
logger.info("Setting global commands");
122122
try {
123123
await client.application!.commands.set(APICommands);
124124
} catch (e) {
125-
error("bot.setCommand", e);
125+
handleError("bot.setCommand", e);
126126
}
127-
report("Setting global commands done");
127+
logger.info("Setting global commands done");
128128
}
129129

130130
const createDeleteButton = (locale: Locale) => new LActionRowDataLocalizer({
@@ -143,7 +143,7 @@ try {
143143
const sources: Record<string, string> = {};
144144

145145
// Linked list storing all interaction ids and it's parent, null if it's the root
146-
const timeouts: Record<string, NodeJS.Timeout> = {};
146+
const timeouts: Record<string, Timer> = {};
147147

148148
client.on("interactionCreate", async (interaction) => {
149149
if (!interaction.isRepliable()) {
@@ -310,7 +310,7 @@ try {
310310
await command.onCommand(interaction)
311311
).build(locale);
312312
} catch (e) {
313-
error(`commands/${command.name}.onCommand`, e);
313+
handleError(`commands/${command.name}.onCommand`, e);
314314
}
315315

316316
await reply(response, command.onTimeout);
@@ -331,7 +331,7 @@ try {
331331
await command.onContextMenu(interaction)
332332
).build(locale);
333333
} catch (e) {
334-
error(`commands/${command.name}.onContextMenu`, e);
334+
handleError(`commands/${command.name}.onContextMenu`, e);
335335
}
336336

337337
await reply(response, command.onTimeout);
@@ -351,7 +351,7 @@ try {
351351
await command.onContextMenu(interaction)
352352
).build(locale);
353353
} catch (e) {
354-
error(`commands/${command.name}.onContextMenu`, e);
354+
handleError(`commands/${command.name}.onContextMenu`, e);
355355
}
356356

357357
await reply(response, command.onTimeout);
@@ -381,15 +381,15 @@ try {
381381
// TODO: Handle unknown interaction
382382
}
383383
} catch (e) {
384-
error(`commands/${command.name}.${interaction.isButton() ? "onButton" : "onSelectMenu"}`, e);
384+
handleError(`commands/${command.name}.${interaction.isButton() ? "onButton" : "onSelectMenu"}`, e);
385385
}
386386

387387
await reply(response, command.onTimeout);
388388
} else if (interaction.isModalSubmit()) {
389389
// TODO: Modal submit
390390
}
391391
} catch (e) {
392-
error("client->interactionCreate", e);
392+
handleError("client->interactionCreate", e);
393393
await reply(generalErrorReply);
394394
}
395395
});
@@ -461,16 +461,16 @@ try {
461461
if (_result) break;
462462
}
463463
} catch (e) {
464-
error(`modules/${module.name}.${event}`, e);
464+
handleError(`modules/${module.name}.${event}`, e);
465465
}
466466
}
467467
});
468468
}
469469

470-
report(`Logged in as ${client.user!.tag}!`);
470+
logger.info(`Logged in as ${client.user!.tag}!`);
471471
});
472472

473473
client.login(process.env.TOKEN);
474474
} catch (e) {
475-
console.error("client", e);
475+
logger.error("client", e);
476476
}

0 commit comments

Comments
 (0)