Skip to content

Commit

Permalink
feat: add better help command and command module
Browse files Browse the repository at this point in the history
  • Loading branch information
Nadim147c committed Sep 4, 2024
1 parent 08f832e commit 2c267c9
Show file tree
Hide file tree
Showing 17 changed files with 255 additions and 199 deletions.
21 changes: 9 additions & 12 deletions biome.json
Original file line number Diff line number Diff line change
@@ -1,15 +1,21 @@
{
"$schema": "https://biomejs.dev/schemas/1.8.3/schema.json",
"organizeImports": { "enabled": true },
"formatter": {
"enabled": true,
"lineWidth": 100,
"lineEnding": "lf",
"indentWidth": 4,
"indentStyle": "space",
"formatWithErrors": true
},
"javascript": {
"formatter": {
"semicolons": "asNeeded",
"quoteStyle": "double",
"trailingCommas": "es5"
}
},
"organizeImports": {
"enabled": true
},
"json": {
"formatter": {
"enabled": true,
Expand All @@ -19,14 +25,6 @@
"indentStyle": "space"
}
},
"formatter": {
"enabled": true,
"lineWidth": 100,
"lineEnding": "lf",
"indentWidth": 4,
"indentStyle": "space",
"formatWithErrors": true
},
"linter": {
"ignore": ["dist", "**/dist", "commitlint.config.js", "pre-commit.js"],
"enabled": true,
Expand Down Expand Up @@ -83,7 +81,6 @@
"useConst": "error"
},
"suspicious": {
"noConsoleLog": "info",
"noAsyncPromiseExecutor": "error",
"noCatchAssign": "error",
"noClassAssign": "error",
Expand Down
Binary file modified bun.lockb
Binary file not shown.
25 changes: 13 additions & 12 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,16 @@
"main": "src/index.ts",
"scripts": {
"start": "bun run dist/index.js",
"build:start": "bun exec tsc && bun run dist/.",
"build:start": "bun run --bun tsc && bun run dist/.",
"nodemon": "nodemon dist/.",
"dev": "bun run --watch src/index.ts",
"build": "tsc",
"watch": "tsc -w",
"build": "bun run --bun tsc",
"watch": "bun run --bun tsc -w",
"prepare": "bunx husky",
"lint": "biome lint",
"lint:fix": "biome lint --fix",
"lint": "biome lint --no-errors-on-unmatched",
"lint:fix": "biome lint --fix --no-errors-on-unmatched",
"format": "biome check --write --no-errors-on-unmatched --linter-enabled=false --formatter-enabled=true --organize-imports-enabled=true",
"ci": "biome ci --no-errors-on-unmatched --formatter-enabled=true --linter-enabled=true --organize-imports-enabled=true ."
"ci": "biome ci --no-errors-on-unmatched --formatter-enabled=true --linter-enabled=true --organize-imports-enabled=true"
},
"lint-staged": {
"*.{ts,cts,mts,js,cjs,mjs}": "biome lint --fix",
Expand All @@ -26,16 +26,17 @@
"license": "MIT",
"devDependencies": {
"@biomejs/biome": "^1.8.3",
"@commitlint/cli": "^19.4.0",
"@commitlint/config-conventional": "^19.2.2",
"@commitlint/cli": "^19.4.1",
"@commitlint/config-conventional": "^19.4.1",
"@types/bun": "^1.1.8",
"@types/glob": "^8.1.0",
"@types/node": "^22.5.0",
"commitlint": "^19.4.0",
"@types/node": "^22.5.3",
"commitlint": "^19.4.1",
"typescript": "^5.5.4"
},
"dependencies": {
"chalk": "^4.1.2",
"discord.js": "^14.15.3",
"chalk": "^5.3.0",
"discord.js": "^14.16.1",
"dotenv": "^16.4.5",
"glob": "^11.0.0",
"smol-toml": "^1.3.0",
Expand Down
47 changes: 47 additions & 0 deletions src/commands/Miscellaneous/help/command/list.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { EmbedBuilder, type EmbedField, codeBlock } from "discord.js"
import { string } from "zod"
import Command from "../../../../structures/Command.js"
import type { CommandType } from "../../../../typings/Commands.js"

// A sub commands of help
export default new Command({
data: {
name: "list",
description: "Get a list of all available commands.",
},
async run(command) {
const commands = Array.from(command.client.commands)

if (commands.length < 1) return await command.reply("There are no commands available")

type SimplifiedHelpCommand = { name: string; body: CommandType }
const helpMap = new Map<string, SimplifiedHelpCommand[]>()
for (const [name, body] of commands) {
const commandHelp = { name, body }

// biome-ignore lint/style/noNonNullAssertion: Categories are set during command modules register
const category = body.category!

const existingCommandHelp = helpMap.get(category)
if (Array.isArray(existingCommandHelp)) {
helpMap.set(category, [...existingCommandHelp, commandHelp])
} else {
helpMap.set(category, [commandHelp])
}
}

const helpArr = Array.from(helpMap).sort(([categoryA], [categoryB]) => {
return categoryA.localeCompare(categoryB)
})

let content = "## List of all available commands"
for (const [category, commands] of helpArr) {
content += `\n### ${category}`
for (const cmd of commands.toSorted((a, b) => a.name.localeCompare(b.name))) {
content += `\n\`/${cmd.name.replace("-", " ")}\`: ${cmd.body.data.description}`
}
}

await command.reply(content)
},
})
39 changes: 0 additions & 39 deletions src/commands/Miscellaneous/help/commands.ts

This file was deleted.

7 changes: 6 additions & 1 deletion src/events/ready.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,12 @@ export default new Event("ready", async (baseClient) => {
// HACK: This one just for setting proper type
const client = baseClient as ExtendedClient
LogStart(client)

for (const guildId of global.config.devGuilds) {
await client.registerCommands(guildId)
try {
await client.registerCommands(guildId)
} catch (error) {
console.error(error)
}
}
})
11 changes: 11 additions & 0 deletions src/functions/log/Color.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import chalk from "chalk"

export default class Print {
static title(...text: unknown[]) {
console.log(chalk.bold(chalk.green(...text)))
}

static gray(...text: unknown[]) {
console.log(chalk.bold(chalk.gray(...text)))
}
}
7 changes: 3 additions & 4 deletions src/functions/log/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,20 @@ import chalk from "chalk"
import { type DateResolvable, EmbedBuilder, type Guild, WebhookClient } from "discord.js"
import type ExtendedClient from "../../structures/Client.js"
import { getDynamicTime } from "../discord/getDynamicTime.js"
import Print from "./Color.js"

const detailedTime = (date: DateResolvable | null | undefined) =>
date ? `${getDynamicTime(date, "LONG_TIME_AND_DATE")} ${getDynamicTime(date, "RELATIVE")}` : ""

export const coloredLog = (text: string, color: string) => {
// biome-ignore lint/suspicious/noConsoleLog: Log
console.log(chalk.hex(color)(text))
}
export const logSuccess = (str: string) => coloredLog(str, "#0f0")
export const LogFail = (str: string | Error) => {
coloredLog(typeof str === "string" ? str : str.message, "#f00")
}

export const LogStart = (client: ExtendedClient) => {
logSuccess(`${client.user.username} is ready.`)
Print.title(`[Ready] ${client.user.username}:${client.user.id}.`)
if (!process.env.LOGIN) return
const webhook = new WebhookClient({ url: process.env.LOGIN })

Expand Down Expand Up @@ -73,7 +72,7 @@ export const logError = (error: Error | unknown) => {

export const guildLog = (guild: Guild, event: "CREATE" | "DELETE") => {
event === "CREATE"
? logSuccess(`Guild Create: ${guild.name}`)
? Print.title(`Guild Create: ${guild.name}`)
: LogFail(`Guild Remove: ${guild.name}`)

if (!process.env.GUILDS) return
Expand Down
14 changes: 7 additions & 7 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,24 @@
import { config } from "dotenv"
import { z } from "zod"
import { logError } from "./functions/log/logger.js"
import loadConfig from "./loadConfig.js"
import ExtendedClient from "./structures/Client.js"

config()

await loadConfig()

const envSchema = z.object({
DISCORD: z.string(),
})
const envSchema = z.object({ DISCORD: z.string() })

envSchema.parse(process.env)

declare global {
// biome-ignore lint/style/noNamespace: <explanation>
// biome-ignore lint/style/noNamespace: Add typing to environment
namespace NodeJS {
interface ProcessEnv extends z.infer<typeof envSchema> {}
}
}
if (global.config.globalErrorHandling) {
process.on("uncaughtException", (error) => logError(error))
process.on("uncaughtExceptionMonitor", (error) => logError(error))
}

const client = new ExtendedClient()

Expand Down
9 changes: 6 additions & 3 deletions src/loadConfig.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { readFile, writeFile } from "node:fs/promises"
import chalk from "chalk"
import TOML from "smol-toml"
import { z } from "zod"
import { logError } from "./functions/log/logger.js"
Expand All @@ -10,6 +9,7 @@ const configSchema = z
developers: z.array(z.string()),
testers: z.array(z.string()),
commandTimeout: z.number(),
globalErrorHandling: z.boolean(),
color: z.number(),
colors: z.object({
default: z.number(),
Expand Down Expand Up @@ -46,19 +46,22 @@ export default async function loadConfig() {
logError(config.error)
process.exit(1)
}
} catch (_error) {
} catch (error) {
console.error(error)

const data = TOML.stringify({
devGuilds: [],
developers: [],
testers: [],
commandTimeout: 5_000,
globalErrorHandling: true,
color: 0x2f3136,
colors: {
default: 0x2f3136,
warn: 0xffff00,
error: 0xff0000,
},
})
} satisfies z.infer<typeof configSchema>)

await writeFile("./config.toml", data, "utf8")
}
Expand Down
11 changes: 8 additions & 3 deletions src/modules/buttons.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
import { srcDir } from "../dirname.js"
import Print from "../functions/log/Color.js"
import type ExtendedClient from "../structures/Client.js"
import type { ButtonType } from "../typings/Buttons.js"

export default async (client: ExtendedClient) => {
const path = `${srcDir}/interaction/buttons`

const files = await client.getFiles(path)
Print.title("[Module]", "loading Buttons")

const buttons: ButtonType[] = await Promise.all(files.map((file) => client.importFile(file)))
const files = await client.getFiles(path)

for (const button of buttons) client.buttons.set(button.id, button)
for await (const file of files) {
const button = (await client.importFile(file)) as ButtonType
Print.gray("[Button]", `ID:${button.id}`)
client.buttons.set(button.id, button)
}
}
Loading

0 comments on commit 2c267c9

Please sign in to comment.