refactor: lint & format

This commit is contained in:
Erica Marigold 2022-11-22 15:13:25 +05:30
parent 9ed5351280
commit aadb93fe9e
No known key found for this signature in database
GPG key ID: 23CD97ABBBCC5ED2
21 changed files with 351 additions and 334 deletions

View file

@ -5,4 +5,3 @@
<a href="https://p.devcomp.xyz/blog/create-guilded-bot"> <img alt="website" height="45" src="https://cdn.jsdelivr.net/npm/@intergrav/devins-badges@2/assets/cozy/documentation/website_vector.svg"> </a>
<a href="https://github.com/sponsors/CompeyDev"> <img alt="ghsponsors-singular" height="45" src="https://cdn.jsdelivr.net/npm/@intergrav/devins-badges@2/assets/cozy/donate/ghsponsors-singular_vector.svg"> </a>
</div>

View file

@ -1,5 +1,6 @@
# `📂common`
A directory consisting shared libraries among packages, namely:
- [`eslint-config-custom`](https://github.com/CompeyDev/create-guilded-bot/tree/main/common/eslint-config-custom) - Custom ESLint Configuration, extending with turbo and prettier rules.
- [`tsconfig`](https://github.com/CompeyDev/create-guilded-bot/tree/main/common/tsconfig) - Shared tsconfigs for various packages.
- [`eslint-config-custom`](https://github.com/CompeyDev/create-guilded-bot/tree/main/common/eslint-config-custom) - Custom ESLint Configuration, extending with turbo and prettier rules.
- [`tsconfig`](https://github.com/CompeyDev/create-guilded-bot/tree/main/common/tsconfig) - Shared tsconfigs for various packages.

View file

@ -1,6 +1,8 @@
# `📂packages`
This directory consists of the main packages of create-guilded-bot, including the framework & the CLI.
## Development
In order to run a development server for all packages concurrently, consider running `pnpm dev` in the monorepo root. Turbo will start a dev server for all required packages.
In case you would like to run a standalone development server for a specific package, `cd` into the package directory and run `pnpm dev`. This should start a dev server for that package.

View file

@ -6,11 +6,12 @@ A CLI to quickly generate & bootstrap guilded.js bot projects. This tool enables
npx create-guilded-bot@latest
# yarn
yarn create guilded-bot
# pnpm
# pnpm
pnpm create guilded-bot
```
You will be asked the following questions:
```bash
✔ Where should the project be initialized? … Directory
✔ Which flavor? … TypeScript/JavaScript

View file

@ -1,28 +1,32 @@
import * as fs from 'fs'
import * as path from 'path'
import { cwd } from 'process'
import * as https from 'https'
import axios from 'axios'
import kleur from 'kleur'
import gradient from 'gradient-string'
import * as fs from "fs";
import * as path from "path";
import { cwd } from "process";
import * as https from "https";
import axios from "axios";
import kleur from "kleur";
import gradient from "gradient-string";
export const c = {
// Welcome message is only accessable by files in lib,
// else it throws an error.
word_CreateAscii: " _ \n | | \n ___ _ __ ___ __ _| |_ ___ \n / __| \'__/ _ \\/ _` | __/ _ \\\n | (__| | | __/ (_| | || __/\n \\___|_| \\___|\\__,_|\\__\\___|",
word_GuildedAscii: " _ _ _ _ \n (_) | | | | |\n __ _ _ _ _| | __| | ___ __| |\n / _` | | | | | |/ _` |/ _ \\/ _` |\n | (_| | |_| | | | (_| | __/ (_| |\n \\__, |\\__,_|_|_|\\__,_|\\___|\\__,_|\n __/ | \n |___/ ",
word_BotAscii: " _ _ \n | | | | \n | |__ ___ | |_ \n | \'_ \\ / _ \\| __|\n | |_) | (_) | |_ \n |_.__/ \\___/ \\__|",
word_HyphenAscii: " \n \n ______ \n |______|\n \n \n \n ",
welcomeMessage: gradient.rainbow.multiline(" _ _ _ _ _ _ _ \n | | (_) | | | | | | | | | \n ___ _ __ ___ __ _| |_ ___ ______ __ _ _ _ _| | __| | ___ __| |______| |__ ___ | |_ \n / __| \'__/ _ \\/ _` | __/ _ \\______/ _` | | | | | |/ _` |/ _ \\/ _` |______| \'_ \\ / _ \\| __|\n | (__| | | __/ (_| | || __/ | (_| | |_| | | | (_| | __/ (_| | | |_) | (_) | |_ \n \\___|_| \\___|\\__,_|\\__\\___| \\__, |\\__,_|_|_|\\__,_|\\___|\\__,_| |_.__/ \\___/ \\__|\n __/ | \n |___/ \n\n")
// Welcome message is only accessable by files in lib,
// else it throws an error.
word_CreateAscii:
" _ \n | | \n ___ _ __ ___ __ _| |_ ___ \n / __| '__/ _ \\/ _` | __/ _ \\\n | (__| | | __/ (_| | || __/\n \\___|_| \\___|\\__,_|\\__\\___|",
word_GuildedAscii:
" _ _ _ _ \n (_) | | | | |\n __ _ _ _ _| | __| | ___ __| |\n / _` | | | | | |/ _` |/ _ \\/ _` |\n | (_| | |_| | | | (_| | __/ (_| |\n \\__, |\\__,_|_|_|\\__,_|\\___|\\__,_|\n __/ | \n |___/ ",
word_BotAscii:
" _ _ \n | | | | \n | |__ ___ | |_ \n | '_ \\ / _ \\| __|\n | |_) | (_) | |_ \n |_.__/ \\___/ \\__|",
word_HyphenAscii:
" \n \n ______ \n |______|\n \n \n \n ",
welcomeMessage: gradient.rainbow.multiline(
" _ _ _ _ _ _ _ \n | | (_) | | | | | | | | | \n ___ _ __ ___ __ _| |_ ___ ______ __ _ _ _ _| | __| | ___ __| |______| |__ ___ | |_ \n / __| '__/ _ \\/ _` | __/ _ \\______/ _` | | | | | |/ _` |/ _ \\/ _` |______| '_ \\ / _ \\| __|\n | (__| | | __/ (_| | || __/ | (_| | |_| | | | (_| | __/ (_| | | |_) | (_) | |_ \n \\___|_| \\___|\\__,_|\\__\\___| \\__, |\\__,_|_|_|\\__,_|\\___|\\__,_| |_.__/ \\___/ \\__|\n __/ | \n |___/ \n\n"
),
} as const;
} as const
const hyphen = kleur.yellow(c.word_HyphenAscii)
const styleGreen = kleur.green
const hyphen = kleur.yellow(c.word_HyphenAscii);
const styleGreen = kleur.green;
// c.welcomeMessage = styleGreen(c.word_CreateAscii.trimEnd()) + hyphen + styleGreen(c.word_GuildedAscii.trimEnd()) + styleGreen(c.word_BotAscii.trimEnd())
export default function getConstant(constant: keyof typeof c): string {
return c[constant]
}
return c[constant];
}

View file

@ -1,10 +1,10 @@
export default function get(): string|null {
const userAgent = process.env.npm_config_user_agent
if (!userAgent) {
return null;
}
export default function get(): string | null {
const userAgent = process.env.npm_config_user_agent;
if (!userAgent) {
return null;
}
const manager = userAgent.split(" ")[0].split("/")[0];
const manager = userAgent.split(" ")[0].split("/")[0];
return manager
}
return manager;
}

View file

@ -1,87 +1,97 @@
import { exec, spawn } from "child_process";
import { platform, userInfo } from "os";
import * as logger from "../utils/logger"
import * as logger from "../utils/logger";
export default function install(
packageManager: "npm" | "pnpm" | "yarn" | null,
workingDirectory: string
) {
const cmds = {
npm: {
win32: {
command: "npm.cmd",
args: ["install"],
full: "npm.cmd install",
},
export default function install(packageManager: "npm" | "pnpm" | "yarn" | null, workingDirectory: string) {
const cmds = {
npm: {
win32: {
command: "npm.cmd",
args: ["install"],
full: "npm.cmd install"
},
linux: {
command: "npm.cmd",
args: ["install"],
full: "npm install",
},
linux: {
command: "npm.cmd",
args: ["install"],
full: "npm install"
},
darwin: {
command: "npm",
args: ["install"],
full: "npm install",
},
},
pnpm: {
win32: {
command: "pnpm.cmd",
args: ["i"],
full: "pnpm.cmd install",
},
darwin: {
command: "npm",
args: ["install"],
full: "npm install"
}
},
pnpm: {
win32: {
command: "pnpm.cmd",
args: ["i"],
full: "pnpm.cmd install"
},
linux: {
command: "pnpm",
args: ["i"],
full: "pnpm install",
},
linux: {
command: "pnpm",
args: ["i"],
full: "pnpm install"
},
darwin: {
command: "pnpm",
args: ["i"],
full: "pnpm install",
},
},
yarn: {
win32: {
command: "yarn.cmd",
args: [],
full: "yarn.cmd",
},
darwin: {
command: "pnpm",
args: ["i"],
full: "pnpm install"
}
},
yarn: {
win32: {
command: "yarn.cmd",
args: [],
full: "yarn.cmd"
},
linux: {
command: "yarn",
args: [],
full: "yarn",
},
linux: {
command: "yarn",
args: [],
full: "yarn"
},
darwin: {
command: "yarn",
args: [],
full: "yarn",
},
},
};
switch (packageManager) {
case null:
exec("npm config set color always");
logger.info("Installing dependencies with npm.");
const spawnedNPM = spawn(
`${cmds.npm[platform()].command}`,
cmds.npm[platform()].args,
{ cwd: workingDirectory }
);
darwin: {
command: "yarn",
args: [],
full: "yarn"
}
}
}
switch (packageManager) {
case null:
exec("npm config set color always")
logger.info("Installing dependencies with npm.")
const spawnedNPM = spawn(`${cmds.npm[platform()].command}`, cmds.npm[platform()].args, { cwd: workingDirectory })
spawnedNPM.stdout.on("data", (out) => {
logger.custom("npm", out.toString().trim());
});
default:
logger.info(`Installing dependencies with ${packageManager}`);
const spawnedAny = spawn(
`${cmds[packageManager][platform()].command}`,
cmds[packageManager][platform()].args,
{ cwd: workingDirectory }
);
spawnedNPM.stdout.on("data", (out) => {
logger.custom("npm", out.toString().trim())
})
default:
logger.info(`Installing dependencies with ${packageManager}`)
const spawnedAny = spawn(`${cmds[packageManager][platform()].command}`, cmds[packageManager][platform()].args, { cwd: workingDirectory })
spawnedAny.stdout.on("data", (out) => {
logger.custom(packageManager, out.toString().trim());
});
spawnedAny.stdout.on("data", (out) => {
logger.custom(packageManager, out.toString().trim())
})
spawnedAny.stderr.on("data", (err) => {
logger.customError(packageManager, err.toString().trim())
})
}
}
spawnedAny.stderr.on("data", (err) => {
logger.customError(packageManager, err.toString().trim());
});
}
}

View file

@ -1,10 +1,10 @@
import * as logger from "../utils/logger"
import * as logger from "../utils/logger";
export default function verify() {
const NODE_VERSION = process.version.split("v")[1] as unknown as number
const NODE_VERSION = process.version.split("v")[1] as unknown as number;
if (NODE_VERSION !>= 12) {
logger.error(`Detected node ${NODE_VERSION}. At least node v12 required.`)
process.exit(1)
}
}
if (NODE_VERSION! >= 12) {
logger.error(`Detected node ${NODE_VERSION}. At least node v12 required.`);
process.exit(1);
}
}

View file

@ -5,83 +5,90 @@ import { copySync, removeSync } from "fs-extra";
import * as inquirer from "inquirer";
import getPackageManager from "../lib/getPackageManager";
import install from "../lib/installDependencies";
import * as logger from "../utils/logger"
import constants from "../lib/constants"
import * as logger from "../utils/logger";
import constants from "../lib/constants";
import getConstant from "../lib/constants";
import stream from "got";
import unzip from "unzip-stream";
import validateClient from "../lib/validateClient";
const weclomeASCII = getConstant("welcomeMessage")
console.log(weclomeASCII)
const weclomeASCII = getConstant("welcomeMessage");
console.log(weclomeASCII);
inquirer
.prompt([
{
type: "input",
name: "location",
message: "Where should the project be initialized?"
message: "Where should the project be initialized?",
},
{
type: 'list',
name: 'flavor',
message: 'Which flavor?',
choices: ['TypeScript', 'JavaScript'],
type: "list",
name: "flavor",
message: "Which flavor?",
choices: ["TypeScript", "JavaScript"],
filter(val) {
return val.toLowerCase();
},
},
])
.then((answers) => {
validateClient()
validateClient();
mkdir(answers.location, (e) => {
if (e && e.code != "EEXIST") {
logger.error("Failed to create project directory.")
process.exit(1)
logger.error("Failed to create project directory.");
process.exit(1);
}
if (e) {
if (e.code == "EEXIST") {
readdir(answers.location, (_, files) => {
if (files.length) {
logger.error("Directory not empty.")
process.exit(1)
logger.error("Directory not empty.");
process.exit(1);
}
})
});
}
}
})
});
let packageManager = getPackageManager()
let packageManager = getPackageManager();
const start = async (TEMPLATE_DOWNLOAD_URL: string) => {
const download = stream(TEMPLATE_DOWNLOAD_URL, { isStream: true }).pipe(createWriteStream(`${answers.location}/create-guilded-bot_ts.zip`));
const download = stream(TEMPLATE_DOWNLOAD_URL, { isStream: true }).pipe(
createWriteStream(`${answers.location}/create-guilded-bot_ts.zip`)
);
download.on("finish", () => {
fs.createReadStream(`${answers.location}/create-guilded-bot_ts.zip`)
.pipe(unzip.Extract({ path: `${answers.location}` }))
.on("finish", () => {
removeSync(`${answers.location}/create-guilded-bot_ts.zip`)
logger.success("🚀 Let's get started.")
})
removeSync(`${answers.location}/create-guilded-bot_ts.zip`);
logger.success("🚀 Let's get started.");
});
});
};
if (answers.flavor == "typescript") {
const TEMPLATE_DOWNLOAD_URL = "https://files.devcomp.xyz/r/create-guilded-bot_ts.zip"
const TEMPLATE_DOWNLOAD_URL =
"https://files.devcomp.xyz/r/create-guilded-bot_ts.zip";
start(TEMPLATE_DOWNLOAD_URL).then(() => {
install(packageManager as "npm" | "pnpm" | "yarn" | null, answers.location)
})
install(
packageManager as "npm" | "pnpm" | "yarn" | null,
answers.location
);
});
}
if (answers.flavor == "javascript") {
const TEMPLATE_DOWNLOAD_URL = "https://files.devcomp.xyz/r/create-guilded-bot_js.zip"
const TEMPLATE_DOWNLOAD_URL =
"https://files.devcomp.xyz/r/create-guilded-bot_js.zip";
start(TEMPLATE_DOWNLOAD_URL).then(() => {
install(packageManager as "npm" | "pnpm" | "yarn" | null, answers.location)
})
install(
packageManager as "npm" | "pnpm" | "yarn" | null,
answers.location
);
});
}
});

View file

@ -1,30 +1,30 @@
import * as kleur from 'kleur';
import * as kleur from "kleur";
const progressStyle = kleur.bold().gray
const successStyle = kleur.bold().green
const errorStyle = kleur.black().bold().red
const warningStyle = kleur.black().bold().yellow
const progressStyle = kleur.bold().gray;
const successStyle = kleur.bold().green;
const errorStyle = kleur.black().bold().red;
const warningStyle = kleur.black().bold().yellow;
export function warn(log: string) {
console.log(warningStyle(`warning`), " ", log )
console.log(warningStyle(`warning`), " ", log);
}
export function error(log: string) {
console.log(errorStyle(`error`), " ", log )
console.log(errorStyle(`error`), " ", log);
}
export function info(log: string) {
console.log(successStyle(`info`), " ", log )
console.log(successStyle(`info`), " ", log);
}
export function success(log: string) {
console.log(successStyle(`success`), " ", log )
console.log(successStyle(`success`), " ", log);
}
export function custom(customType: string, log: string) {
console.log(progressStyle(`[${customType}] `), log)
console.log(progressStyle(`[${customType}] `), log);
}
export function customError(customType: string, log: string) {
console.log(errorStyle(`[${customType}] error `), log)
}
console.log(errorStyle(`[${customType}] error `), log);
}

View file

@ -1,5 +1,7 @@
# `📦framework`
This directory consists of the core frameworks for both JavaScript and TypeScript, including a shared `tsconfig.json`.
## Development
Running a standalone development server for the TypeScript framework first requires dependencies for the shared tsconfig installed. Dependencies for all packages can be globally installed by running `pnpm i` in the monorepo root.

View file

@ -1,7 +1,9 @@
🚀 This is a guilded bot created using [create-guilded-bot](https://github.com/CompeyDev/create-guilded-bot).
## Getting Started
In order to run the development environment, configure your .env file with the required variables and then execute the following commands:
```bash
npm run dev
# or with yarn
@ -16,7 +18,7 @@ You can start editing the commands by adding/modifying files in the `commands` d
Events can also be customized by adding files to the `events` directory corresponding to the name of the event. See `events/ready.js` for an example event.
## Learn More
Since create-guilded-bot uses guilded.js, you can learn more from their [official docs](https://guilded.js.org/).
##### ✨ This template is highly inspired by reconlx's [djs-typescript-handler](https://github.com/reconlx/djs-typescript-handler), so give them a star :)

View file

@ -1,7 +1,9 @@
🚀 This is a guilded bot created using [create-guilded-bot](https://github.com/CompeyDev/create-guilded-bot).
## Getting Started
In order to run the development environment, configure your .env file with the required variables and then execute the following commands:
```bash
npm run dev
# or with yarn
@ -16,7 +18,7 @@ You can start editing the commands by adding/modifying files in the `commands` d
Events can also be customized by adding files to the `events` directory corresponding to the name of the event. See `events/ready.ts` for an example event.
## Learn More
Since create-guilded-bot uses guilded.js, you can learn more from their [official docs](https://guilded.js.org/).
##### ✨ This template is highly inspired by reconlx's [djs-typescript-handler](https://github.com/reconlx/djs-typescript-handler), so give them a star :)

View file

@ -1,12 +1,12 @@
declare global {
namespace NodeJS {
interface ProcessEnv {
botToken: string;
environment: "dev" | "prod" | "debug";
ownerId: string;
botPrefix: string
}
namespace NodeJS {
interface ProcessEnv {
botToken: string;
environment: "dev" | "prod" | "debug";
ownerId: string;
botPrefix: string;
}
}
}
export {};
export {};

View file

@ -2,9 +2,9 @@ import { client } from "..";
import { Command } from "../structures/Command";
export default new Command({
name: "hello",
description: "Make the bot send a hello world message.",
run: async ({ interaction }) => {
interaction.ctx.reply('Hello, world!')
}
})
name: "hello",
description: "Make the bot send a hello world message.",
run: async ({ interaction }) => {
interaction.ctx.reply("Hello, world!");
},
});

View file

@ -3,43 +3,41 @@ import { client } from "..";
import { Command } from "../structures/Command";
export default new Command({
name: "help",
description: "Get a list of commands.",
run: async ({ interaction }) => {
const options = interaction.ctx.getOptions()
if (!options) {
let fetchedCmds = await client.getCommands()
name: "help",
description: "Get a list of commands.",
run: async ({ interaction }) => {
const options = interaction.ctx.getOptions();
if (!options) {
let fetchedCmds = await client.getCommands();
let stringifiedCommands: string = ""
for (let cmd in fetchedCmds) {
stringifiedCommands += `${fetchedCmds[cmd].name} - ${fetchedCmds[cmd].description}\n`
}
let stringifiedCommands: string = "";
for (let cmd in fetchedCmds) {
stringifiedCommands += `${fetchedCmds[cmd].name} - ${fetchedCmds[cmd].description}\n`;
}
const menu = new Embed({
title: "Available commands",
description: stringifiedCommands,
})
const menu = new Embed({
title: "Available commands",
description: stringifiedCommands,
});
interaction.ctx.reply(menu)
} else if (options && options.length == 1) {
let fetchedCmds = await client.getCommands()
let stringifiedCommands: string = ""
for (let cmd in fetchedCmds) {
if (fetchedCmds[cmd].name == options[0]) {
stringifiedCommands += `${fetchedCmds[cmd].name} - ${fetchedCmds[cmd].description}`
const menu = new Embed({
title: "Available commands",
description: stringifiedCommands,
})
interaction.ctx.reply(menu);
} else if (options && options.length == 1) {
let fetchedCmds = await client.getCommands();
let stringifiedCommands: string = "";
for (let cmd in fetchedCmds) {
if (fetchedCmds[cmd].name == options[0]) {
stringifiedCommands += `${fetchedCmds[cmd].name} - ${fetchedCmds[cmd].description}`;
const menu = new Embed({
title: "Available commands",
description: stringifiedCommands,
});
interaction.ctx.reply(menu)
return;
}
}
interaction.ctx.reply("No such command exists.")
interaction.ctx.reply(menu);
return;
}
}
interaction.ctx.reply("No such command exists.");
}
})
},
});

View file

@ -1,6 +1,6 @@
import { client } from ".."
import { Event } from "../structures/Event"
import { client } from "..";
import { Event } from "../structures/Event";
export default new Event("ready", () => {
console.log(`${client.user.name} is ready!`)
})
console.log(`${client.user.name} is ready!`);
});

View file

@ -3,4 +3,3 @@ import { ExtendedClient } from "./structures/Client";
export const client = new ExtendedClient();
client.start();

View file

@ -1,127 +1,121 @@
import { Client, ClientEvents } from 'guilded.js'
import { promisify } from 'util'
import glob from 'glob'
import { Event } from './Event'
import { CommandType, ResCtx } from '../typings/command'
const globPromise = promisify(glob)
import { Client, ClientEvents } from "guilded.js";
import { promisify } from "util";
import glob from "glob";
import { Event } from "./Event";
import { CommandType, ResCtx } from "../typings/command";
const globPromise = promisify(glob);
export class ExtendedClient extends Client {
constructor() {
if (!process.env.botToken) return;
super({ token: process.env.botToken })
constructor() {
if (!process.env.botToken) return;
super({ token: process.env.botToken });
}
start() {
this.registerModules();
this.login();
}
// Slash commands would be so cool, guilded!
async importFile(filePath: string) {
return (await import(filePath))?.default;
}
async getCommands() {
const commandFiles = await globPromise(
`${__dirname}/../commands/*{.ts,.js}`
);
const commandsDir: any = new Object();
for (let commandPath of commandFiles) {
const command: CommandType = await this.importFile(commandPath);
const splitted = commandPath.split("/");
const fileName = splitted[splitted.length - 1];
commandsDir[fileName] = {
name: command.name,
description: command.description,
};
}
start() {
this.registerModules()
this.login()
}
return commandsDir;
}
// Slash commands would be so cool, guilded!
registerModules() {
this.registerCommands();
this.registerEvents();
}
async importFile(filePath: string) {
return (await import(filePath))?.default;
}
async registerEvents() {
const eventFiles = await globPromise(`${__dirname}/../events/*{.ts,.js}`);
eventFiles.forEach(async (filePath) => {
const event: Event<keyof ClientEvents> = await this.importFile(filePath);
this.on(event.event, event.run);
});
}
async getCommands() {
const commandFiles = await globPromise(
`${__dirname}/../commands/*{.ts,.js}`
)
const commandsDir: any = new Object()
private async validateCommands() {
let commands = await globPromise(`${__dirname}/../commands/*{.ts,.js}`);
let findDuplicates = (arr: any[]) =>
arr.filter((v: any, i: number) => arr.indexOf(v) != i);
let cmds = new Array();
commands.forEach(async (commandPath) => {
let imported = await this.importFile(commandPath);
cmds.push(imported.name);
if (findDuplicates(cmds).length !== 0) {
throw new Error("Command names must be unique.");
}
});
}
async registerCommands() {
this.validateCommands().then(async () => {
let commandFiles = await globPromise(
`${__dirname}/../commands/*{.ts,.js}`
);
for (let commandPath of commandFiles) {
const command: CommandType = await this.importFile(commandPath)
const splitted = commandPath.split("/")
const fileName = splitted[splitted.length - 1]
commandsDir[fileName] = { name: command.name, description: command.description }
}
return commandsDir
}
registerModules() {
this.registerCommands()
this.registerEvents()
}
async registerEvents() {
const eventFiles = await globPromise(
`${__dirname}/../events/*{.ts,.js}`
)
eventFiles.forEach(async (filePath) => {
const event: Event<keyof ClientEvents> = await this.importFile(
filePath
);
this.on(event.event, event.run);
});
}
private async validateCommands() {
let commands = await globPromise(
`${__dirname}/../commands/*{.ts,.js}`
)
let findDuplicates = (arr: any[]) => arr.filter((v: any, i: number) => arr.indexOf(v) != i)
let cmds = new Array()
commands.forEach(async (commandPath) => {
let imported = await this.importFile(commandPath)
cmds.push(imported.name)
if (findDuplicates(cmds).length !== 0) {
throw new Error("Command names must be unique.")
}
})
}
async registerCommands() {
this.validateCommands().then(async () => {
let commandFiles = await globPromise(
`${__dirname}/../commands/*{.ts,.js}`
)
this.on("messageCreated", async (message) => {
if (message.content.startsWith(process.env.botPrefix)) {
for (let filepath of commandFiles) {
const command = await this.importFile(filepath)
const parsed = message.content.split(" ")
const args = parsed.filter((_, i) => { return i > 0 })
if (command.name === parsed[0].split(process.env.botPrefix)[1]) {
if (!message.serverId) throw new Error("Failed to fetch message serverId!")
const Context: ResCtx = {
meta:
{
user: await this.members.fetch(message.serverId, message.authorId),
raw: message,
},
ctx:
{
getOptions: () => {
if (args.length != 0) {
return args
} else {
return null
}
},
reply: (content) => { message.reply(content) }
}
}
command.run({ interaction: Context })
return;
}
this.on("messageCreated", async (message) => {
if (message.content.startsWith(process.env.botPrefix)) {
for (let filepath of commandFiles) {
const command = await this.importFile(filepath);
const parsed = message.content.split(" ");
const args = parsed.filter((_, i) => {
return i > 0;
});
if (command.name === parsed[0].split(process.env.botPrefix)[1]) {
if (!message.serverId)
throw new Error("Failed to fetch message serverId!");
const Context: ResCtx = {
meta: {
user: await this.members.fetch(
message.serverId,
message.authorId
),
raw: message,
},
ctx: {
getOptions: () => {
if (args.length != 0) {
return args;
} else {
return null;
}
message.reply("Requested command does not exist!")
}
})
})
}
}
},
reply: (content) => {
message.reply(content);
},
},
};
command.run({ interaction: Context });
return;
}
}
message.reply("Requested command does not exist!");
}
});
});
}
}

View file

@ -1,8 +1,7 @@
import { CommandType, ResCtx } from "../typings/command";
export class Command {
constructor(commandOptions: CommandType) {
Object.assign(this, commandOptions);
}
constructor(commandOptions: CommandType) {
Object.assign(this, commandOptions);
}
}

View file

@ -1,8 +1,5 @@
import { ClientEvents } from "guilded.js";
export class Event<Key extends keyof ClientEvents> {
constructor(
public event: Key,
public run: (...args: any) => any
) {}
}
constructor(public event: Key, public run: (...args: any) => any) {}
}