Skip to content

Commit

Permalink
fixed bot.ts config imports
Browse files Browse the repository at this point in the history
  • Loading branch information
GhomKrosmonaute committed Apr 25, 2024
1 parent 8dbe147 commit 8f506db
Show file tree
Hide file tree
Showing 14 changed files with 107 additions and 67 deletions.
15 changes: 12 additions & 3 deletions src/app/client.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,17 @@
// system file, please don't modify it

import discord from "discord.js"
import { config } from "../config.js"
import * as config from "./config.js"

export const client = new discord.Client(config.client)
export class ClientSingleton {
private static instance: discord.Client

export default client
private constructor() {}

static get(): discord.Client {
if (!ClientSingleton.instance) {
ClientSingleton.instance = new discord.Client(config.getConfig().client)
}
return ClientSingleton.instance
}
}
11 changes: 6 additions & 5 deletions src/app/command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,7 @@ import * as handler from "@ghom/handler"
import * as util from "./util.js"
import * as logger from "./logger.js"
import * as argument from "./argument.js"

import { config } from "../config.js"
import * as config from "./config.js"

import { filename } from "dirname-filename-esm"

Expand Down Expand Up @@ -839,8 +838,10 @@ export async function sendCommandDetails(
message: IMessage,
cmd: ICommand,
): Promise<void> {
if (config.detailCommand) {
const options = await config.detailCommand(message, cmd)
const { detailCommand, openSource } = config.getConfig()

if (detailCommand) {
const options = await detailCommand(message, cmd)
await message.channel.send(options)

return
Expand All @@ -860,7 +861,7 @@ export async function sendCommandDetails(

const breadcrumb = commandBreadcrumb(cmd)

if (config.openSource && util.packageJSON.repository?.url && cmd.filepath) {
if (openSource && util.packageJSON.repository?.url && cmd.filepath) {
let url = commandGitURLs.get(breadcrumb)

if (!url) url = await util.getFileGitURL(cmd.filepath)
Expand Down
20 changes: 19 additions & 1 deletion src/app/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@ import type * as discord from "discord.js"
import type * as pagination from "./pagination.js"
import type * as command from "./command.js"
import type * as slash from "./slash.js"
import type * as util from "./util.js"

import * as util from "./util.js"

import { config } from "../config.js"

export interface Config {
/**
Expand Down Expand Up @@ -65,3 +68,18 @@ export interface Config {
*/
systemMessages?: Partial<util.SystemMessages>
}

const finalConfig: {
data: Config | null
} = {
data: null,
}

export function getConfig() {
if (!finalConfig.data) throw new Error("Config not initialized")
return finalConfig.data
}

export async function initConfig() {
finalConfig.data = await util.scrap(config)
}
29 changes: 17 additions & 12 deletions src/app/listener.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import apiTypes from "discord-api-types/v8.js"
import * as handler from "@ghom/handler"

import * as logger from "./logger.js"
import client from "./client.js"
import * as client from "./client.js"

const readyListeners = new discord.Collection<Listener<"ready">, boolean>()

Expand All @@ -22,23 +22,28 @@ export const listenerHandler = new handler.Handler(
return file.default as Listener<any>
},
onLoad: async (filepath, listener) => {
const clientInstance = client.ClientSingleton.get()

if (listener.event === "ready") readyListeners.set(listener, false)

client[listener.once ? "once" : "on"](listener.event, async (...args) => {
try {
await listener.run(...args)
clientInstance[listener.once ? "once" : "on"](
listener.event,
async (...args) => {
try {
await listener.run(...args)

if (listener.event === "ready") {
readyListeners.set(listener, true)
if (listener.event === "ready") {
readyListeners.set(listener, true)

if (readyListeners.every((launched) => launched)) {
client.emit("afterReady", ...args)
if (readyListeners.every((launched) => launched)) {
clientInstance.emit("afterReady", ...args)
}
}
} catch (error: any) {
logger.error(error, filepath, true)
}
} catch (error: any) {
logger.error(error, filepath, true)
}
})
},
)

const isNative = filepath.includes(".native.")

Expand Down
10 changes: 7 additions & 3 deletions src/app/pagination.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,9 @@
import discord from "discord.js"

import * as logger from "./logger.js"
import * as config from "./config.js"
import * as util from "./util.js"

import { config } from "../config.js"

import { filename } from "dirname-filename-esm"

const __filename = filename(import.meta)
Expand Down Expand Up @@ -52,7 +51,7 @@ export abstract class Paginator {
static instances: Paginator[] = []
static defaultPlaceHolder = "Oops, no data found"
static keys: PaginatorKey[] = ["start", "previous", "next", "end"]
static defaultEmojis: PaginatorEmojis = config.paginatorEmojis ?? {
static defaultEmojis: PaginatorEmojis = {
previous: "◀️",
next: "▶️",
start: "⏪",
Expand Down Expand Up @@ -314,3 +313,8 @@ export class StaticPaginator extends Paginator {
)
}
}

export async function initPagination() {
const { paginatorEmojis } = config.getConfig()
if (paginatorEmojis) Paginator.defaultEmojis = paginatorEmojis
}
9 changes: 5 additions & 4 deletions src/app/slash.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,9 @@ import chalk from "chalk"

import * as handler from "@ghom/handler"
import * as logger from "./logger.js"
import * as config from "./config.js"
import * as util from "./util.js"

import { config } from "../config.js"

import { filename } from "dirname-filename-esm"

const __filename = filename(import.meta)
Expand Down Expand Up @@ -396,9 +395,11 @@ export async function sendSlashCommandDetails(
interaction: ISlashCommandInteraction,
computed: discord.ApplicationCommand,
) {
const { detailSlashCommand } = config.getConfig()

interaction.reply(
config.detailSlashCommand
? await config.detailSlashCommand(interaction, computed)
detailSlashCommand
? await detailSlashCommand(interaction, computed)
: {
embeds: [
new discord.EmbedBuilder()
Expand Down
11 changes: 5 additions & 6 deletions src/app/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,7 @@ import timezone from "dayjs/plugin/timezone.js"
import toObject from "dayjs/plugin/toObject.js"

import * as logger from "./logger.js"

import { config } from "../config.js"
import * as config from "./config.js"

export type PermissionsNames = keyof typeof v10.PermissionFlagsBits

Expand Down Expand Up @@ -458,7 +457,7 @@ const defaultSystemEmojis: SystemEmojis = {
}

export function getSystemEmoji(name: keyof SystemEmojis): string {
return config.systemEmojis?.[name] ?? defaultSystemEmojis[name]
return config.getConfig().systemEmojis?.[name] ?? defaultSystemEmojis[name]
}

export interface SystemMessageOptions {
Expand Down Expand Up @@ -624,7 +623,7 @@ export function getSystemMessage<Key extends keyof SystemMessages>(
? Options
: never,
): Promise<SystemMessage> {
return (config.systemMessages?.[name] ?? defaultSystemMessages[name])(
options as any,
)
return (
config.getConfig().systemMessages?.[name] ?? defaultSystemMessages[name]
)(options as any)
}
36 changes: 18 additions & 18 deletions src/config.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,29 @@
import * as app from "./app.js"

export const config: app.Config = {
export const config: app.Scrap<app.Config> = () => ({
ignoreBots: true,
openSource: true,
getPrefix: (message) => {
return app.prefix(message.guild)
},
client: {
intents: [
"Guilds",
"GuildMembers",
"GuildBans",
"GuildEmojisAndStickers",
"GuildIntegrations",
"GuildWebhooks",
"GuildInvites",
"GuildVoiceStates",
"GuildPresences",
"GuildMessages",
"GuildMessageTyping",
"GuildMessageReactions",
"DirectMessages",
"DirectMessageTyping",
"DirectMessageReactions",
"MessageContent",
app.IntentsBitField.Flags.Guilds,
app.IntentsBitField.Flags.GuildMembers,
app.IntentsBitField.Flags.GuildModeration,
app.IntentsBitField.Flags.GuildEmojisAndStickers,
app.IntentsBitField.Flags.GuildIntegrations,
app.IntentsBitField.Flags.GuildWebhooks,
app.IntentsBitField.Flags.GuildInvites,
app.IntentsBitField.Flags.GuildVoiceStates,
app.IntentsBitField.Flags.GuildPresences,
app.IntentsBitField.Flags.GuildMessages,
app.IntentsBitField.Flags.GuildMessageTyping,
app.IntentsBitField.Flags.GuildMessageReactions,
app.IntentsBitField.Flags.DirectMessages,
app.IntentsBitField.Flags.DirectMessageTyping,
app.IntentsBitField.Flags.DirectMessageReactions,
app.IntentsBitField.Flags.MessageContent,
],
},
paginatorEmojis: {
Expand All @@ -37,4 +37,4 @@ export const config: app.Config = {
error: app.Emotes.Cross,
loading: app.Emotes.Loading,
},
}
})
4 changes: 3 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,13 @@ const app = await import("./app.js")

try {
await app.orm.init()
await app.initConfig()
await app.commandHandler.init()
await app.slashCommandHandler.init()
await app.listenerHandler.init()
await app.initPagination()
await app.checkUpdates()
await app.client.login(process.env.BOT_TOKEN)
await app.ClientSingleton.get().login(process.env.BOT_TOKEN)
} catch (error: any) {
app.error(error, __filename, true)
process.exit(1)
Expand Down
4 changes: 1 addition & 3 deletions src/listeners/clean.guildMemberRemove.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import * as app from "../app.js"

import client from "../app/client.js"

import users from "../tables/user.js"

const listener: app.Listener<"guildMemberRemove"> = {
Expand All @@ -16,7 +14,7 @@ const listener: app.Listener<"guildMemberRemove"> = {
const user = await member.client.users.fetch(member.id)

if (
client.guilds.cache
member.client.guilds.cache
.filter((g) => g.id !== guild.id)
.every((g) => !g.members.cache.has(member.id))
)
Expand Down
18 changes: 9 additions & 9 deletions src/listeners/command.messageCreate.native.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,21 @@ const listener: app.Listener<"messageCreate"> = {
event: "messageCreate",
description: "Handle messages for commands",
async run(message) {
if (app.config.ignoreBots && message.author.bot) return
const config = app.getConfig()

if (config.ignoreBots && message.author.bot) return

if (!app.isNormalMessage(message)) return

const prefix = await app.config.getPrefix(message)
const prefix = await config.getPrefix(message)

if (new RegExp(`^<@!?${message.client.user.id}>$`).test(message.content))
return message.channel
.send({
embeds: [
new app.EmbedBuilder()
.setColor("Blurple")
.setDescription(`My prefix is \`${prefix}\``),
],
})
.send(
await app.getSystemMessage("default", {
description: `My prefix is \`${prefix}\``,
}),
)
.catch()

message.usedAsDefault = false
Expand Down
3 changes: 2 additions & 1 deletion src/namespaces/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,8 @@ export async function getUser(user: { id: string }, force?: true) {
await users.query
.insert({
id: user.id,
is_bot: app.client.users.cache.get(user.id)?.bot ?? false,
is_bot:
app.ClientSingleton.get().users.cache.get(user.id)?.bot ?? false,
})
.onConflict("id")
.merge()
Expand Down
2 changes: 1 addition & 1 deletion src/slash/ping.native.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ export default new app.SlashCommand({
description: "Get the bot ping",
run(interaction) {
return interaction.reply({
content: `Pong! \`${app.client.ws.ping}ms\``,
content: `Pong! \`${app.ClientSingleton.get().ws.ping}ms\``,
ephemeral: true,
})
},
Expand Down
2 changes: 2 additions & 0 deletions tests/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@ const app = await import("../dist/app.js")

try {
await app.orm.handler.init()
await app.initConfig()
await app.commandHandler.init()
await app.slashCommandHandler.init()
await app.listenerHandler.init()
await app.initPagination()
await app.checkUpdates()

app.log("correctly started")
Expand Down

0 comments on commit 8f506db

Please sign in to comment.