Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(#59): disable discord error logs in dev mode #65

Merged
merged 1 commit into from
Sep 12, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/commands/General/ping.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export default class PingCommand {
member: msg.inGuild() ? `${interaction.member},` : "",
time: msg.createdTimestamp - interaction.createdTimestamp,
heartbeat: client.ws.ping ? `The heartbeat ping is ${Math.round(client.ws.ping)}ms.` : ""
});
})

await msg.edit(content)
}
Expand Down
3 changes: 2 additions & 1 deletion src/events/interactionCreate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,9 @@ export default class InteractionCreateEvent {
[interaction]: ArgsOf<'interactionCreate'>,
client: Client
) {

// defer the reply
if(interaction instanceof CommandInteraction) await interaction.deferReply()
if (interaction instanceof CommandInteraction) await interaction.deferReply()

// insert user in db if not exists
await syncUser(interaction.user)
Expand Down
2 changes: 1 addition & 1 deletion src/services/ErrorHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export class ErrorHandler {
process.on('unhandledRejection', (error: Error | any, promise: Promise<any>) => {

// if instance of BaseError, call `handle` method
if(error instanceof BaseError) return error.handle()
if (error instanceof BaseError) return error.handle()

// log the error
this.logger.logError(error, "unhandledRejection")
Expand Down
11 changes: 6 additions & 5 deletions src/services/Logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,8 @@ export class Logger {


async discordChannel(channelId: string, message: string | MessageOptions = '', level?: typeof this.levels[number]) {
if(!this.client.token) return

if (!this.client.token) return

const channel = await this.client.channels.fetch(channelId)

Expand Down Expand Up @@ -232,13 +233,13 @@ export class Logger {
let embedTitle = ''
let chalkedMessage = `(${chalk.bold.white('ERROR')})`

if(trace && trace[0]) {
if (trace && trace[0]) {
message += ` ${type === 'Exception' ? 'Exception' : 'Unhandled rejection'} : ${error.message}\n${trace.map((frame: StackFrame) => `\t> ${frame.file}:${frame.lineNumber}`).join('\n')}`
embedMessage += `\`\`\`\n${trace.map((frame: StackFrame) => `\> ${frame.file}:${frame.lineNumber}`).join('\n')}\n\`\`\``
embedTitle += `***${type === 'Exception' ? 'Exception' : 'Unhandled rejection'}* : ${error.message}**`
chalkedMessage += ` ${chalk.dim.italic.gray(type === 'Exception' ? 'Exception' : 'Unhandled rejection')} : ${error.message}\n${chalk.dim.italic(trace.map((frame: StackFrame) => `\t> ${frame.file}:${frame.lineNumber}`).join('\n'))}`
} else {
if(type === 'Exception') {
if (type === 'Exception') {
message += `An exception as occured in a unknow file\n\t> ${error.message}`
embedMessage += `An exception as occured in a unknow file\n${error.message}`
} else {
Expand All @@ -247,15 +248,15 @@ export class Logger {
}
}

if(embedMessage.length >= 4096) {
if (embedMessage.length >= 4096) {
const paste = await this.pastebin.createPaste(embedTitle + "\n" + embedMessage)
console.log(paste?.getLink())
embedMessage = `[Pastebin of the error](https://rentry.co/${paste?.getLink()})`
}

if (logsConfig.error.console) this.console('error', chalkedMessage)
if (logsConfig.error.file) this.file('error', message)
if (logsConfig.error.channel) this.discordChannel(logsConfig.error.channel, {
if (logsConfig.error.channel && process.env['NODE_ENV'] === 'production') this.discordChannel(logsConfig.error.channel, {
embeds: [{
title: (embedTitle.length >= 256 ? (embedTitle.substring(0, 252) + "...") : embedTitle),
description: embedMessage,
Expand Down
52 changes: 28 additions & 24 deletions src/services/Pastebin.ts
Original file line number Diff line number Diff line change
@@ -1,62 +1,66 @@
import { Paste, RentryClient } from "rentry-pastebin";
import { singleton } from "tsyringe";
import dayjs from "dayjs";
import { Paste, RentryClient } from "rentry-pastebin"
import { singleton } from "tsyringe"
import dayjs from "dayjs"

import { Pastebin as PastebinEntity } from "@entities";
import { Database } from "@services";
import { Pastebin as PastebinEntity } from "@entities"
import { Database } from "@services"
import { Schedule } from '@decorators'

@singleton()
export class Pastebin {
private client: RentryClient = new RentryClient();
private client: RentryClient = new RentryClient()

constructor(
private db: Database,
) {
this.client.createToken();
this.client.createToken()
}

private async waitForToken(): Promise<void> {

while(!this.client.getToken()) {
await new Promise(resolve => setTimeout(resolve, 100))
}
}

async createPaste(content: string, lifetime?: number): Promise<Paste | undefined> {
await this.waitForToken();

const paste = await this.client.createPaste({ content });
await this.waitForToken()

const paste = await this.client.createPaste({ content })

let pasteEntity = new PastebinEntity();
pasteEntity.id = paste.url;
pasteEntity.editCode = paste.editCode;
if(lifetime) pasteEntity.lifetime = Math.floor(lifetime)
let pasteEntity = new PastebinEntity()
pasteEntity.id = paste.url
pasteEntity.editCode = paste.editCode
if (lifetime) pasteEntity.lifetime = Math.floor(lifetime)

await this.db.getRepo(PastebinEntity).persistAndFlush(pasteEntity);
await this.db.getRepo(PastebinEntity).persistAndFlush(pasteEntity)

return paste.paste;
return paste.paste
}

async deletePaste(id: string): Promise<void> {
await this.waitForToken();

await this.waitForToken()

const paste = await this.db.getRepo(PastebinEntity).findOne({ id });
const paste = await this.db.getRepo(PastebinEntity).findOne({ id })

if(!paste) return;
if (!paste) return

await this.client.deletePaste(id, paste.editCode);
await this.db.getRepo(PastebinEntity).remove(paste);
await this.client.deletePaste(id, paste.editCode)
await this.db.getRepo(PastebinEntity).remove(paste)
}

@Schedule('*/30 * * * *')
private async autoDelete(): Promise<void> {
const pastes = await this.db.getRepo(PastebinEntity).find({ lifetime: { $gt: 0 } });

const pastes = await this.db.getRepo(PastebinEntity).find({ lifetime: { $gt: 0 } })

for(const paste of pastes) {
const diff = dayjs().diff(dayjs(paste.createdAt), 'day');
const diff = dayjs().diff(dayjs(paste.createdAt), 'day')

if(diff >= paste.lifetime) {
await this.client.deletePaste(paste.id, paste.editCode);
if (diff >= paste.lifetime) {
await this.client.deletePaste(paste.id, paste.editCode)
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/utils/functions/error.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { parse } from "stacktrace-parser";
import { parse } from "stacktrace-parser"

export const getCallerFile = (depth: number = 0) => {

Expand Down