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://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> <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> </div>

View file

@ -1,5 +1,6 @@
# `📂common` # `📂common`
A directory consisting shared libraries among packages, namely: 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. - [`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. - [`tsconfig`](https://github.com/CompeyDev/create-guilded-bot/tree/main/common/tsconfig) - Shared tsconfigs for various packages.

View file

@ -1,6 +1,8 @@
# `📂packages` # `📂packages`
This directory consists of the main packages of create-guilded-bot, including the framework & the CLI. This directory consists of the main packages of create-guilded-bot, including the framework & the CLI.
## Development ## 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 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. 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 npx create-guilded-bot@latest
# yarn # yarn
yarn create guilded-bot yarn create guilded-bot
# pnpm # pnpm
pnpm create guilded-bot pnpm create guilded-bot
``` ```
You will be asked the following questions: You will be asked the following questions:
```bash ```bash
✔ Where should the project be initialized? … Directory ✔ Where should the project be initialized? … Directory
✔ Which flavor? … TypeScript/JavaScript ✔ Which flavor? … TypeScript/JavaScript

View file

@ -1,28 +1,32 @@
import * as fs from 'fs' import * as fs from "fs";
import * as path from 'path' import * as path from "path";
import { cwd } from 'process' import { cwd } from "process";
import * as https from 'https' import * as https from "https";
import axios from 'axios' import axios from "axios";
import kleur from 'kleur' import kleur from "kleur";
import gradient from 'gradient-string' import gradient from "gradient-string";
export const c = { export const c = {
// Welcome message is only accessable by files in lib, // Welcome message is only accessable by files in lib,
// else it throws an error. // else it throws an error.
word_CreateAscii: " _ \n | | \n ___ _ __ ___ __ _| |_ ___ \n / __| \'__/ _ \\/ _` | __/ _ \\\n | (__| | | __/ (_| | || __/\n \\___|_| \\___|\\__,_|\\__\\___|", word_CreateAscii:
word_GuildedAscii: " _ _ _ _ \n (_) | | | | |\n __ _ _ _ _| | __| | ___ __| |\n / _` | | | | | |/ _` |/ _ \\/ _` |\n | (_| | |_| | | | (_| | __/ (_| |\n \\__, |\\__,_|_|_|\\__,_|\\___|\\__,_|\n __/ | \n |___/ ", " _ \n | | \n ___ _ __ ___ __ _| |_ ___ \n / __| '__/ _ \\/ _` | __/ _ \\\n | (__| | | __/ (_| | || __/\n \\___|_| \\___|\\__,_|\\__\\___|",
word_BotAscii: " _ _ \n | | | | \n | |__ ___ | |_ \n | \'_ \\ / _ \\| __|\n | |_) | (_) | |_ \n |_.__/ \\___/ \\__|", word_GuildedAscii:
word_HyphenAscii: " \n \n ______ \n |______|\n \n \n \n ", " _ _ _ _ \n (_) | | | | |\n __ _ _ _ _| | __| | ___ __| |\n / _` | | | | | |/ _` |/ _ \\/ _` |\n | (_| | |_| | | | (_| | __/ (_| |\n \\__, |\\__,_|_|_|\\__,_|\\___|\\__,_|\n __/ | \n |___/ ",
welcomeMessage: gradient.rainbow.multiline(" _ _ _ _ _ _ _ \n | | (_) | | | | | | | | | \n ___ _ __ ___ __ _| |_ ___ ______ __ _ _ _ _| | __| | ___ __| |______| |__ ___ | |_ \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()) // 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 { 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 { export default function get(): string | null {
const userAgent = process.env.npm_config_user_agent const userAgent = process.env.npm_config_user_agent;
if (!userAgent) { if (!userAgent) {
return null; 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 { exec, spawn } from "child_process";
import { platform, userInfo } from "os"; 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) { linux: {
const cmds = { command: "npm.cmd",
npm: { args: ["install"],
win32: { full: "npm install",
command: "npm.cmd", },
args: ["install"],
full: "npm.cmd install"
},
linux: { darwin: {
command: "npm.cmd", command: "npm",
args: ["install"], args: ["install"],
full: "npm install" full: "npm install",
}, },
},
pnpm: {
win32: {
command: "pnpm.cmd",
args: ["i"],
full: "pnpm.cmd install",
},
darwin: { linux: {
command: "npm", command: "pnpm",
args: ["install"], args: ["i"],
full: "npm install" full: "pnpm install",
} },
},
pnpm: {
win32: {
command: "pnpm.cmd",
args: ["i"],
full: "pnpm.cmd install"
},
linux: { darwin: {
command: "pnpm", command: "pnpm",
args: ["i"], args: ["i"],
full: "pnpm install" full: "pnpm install",
}, },
},
yarn: {
win32: {
command: "yarn.cmd",
args: [],
full: "yarn.cmd",
},
darwin: { linux: {
command: "pnpm", command: "yarn",
args: ["i"], args: [],
full: "pnpm install" full: "yarn",
} },
},
yarn: {
win32: {
command: "yarn.cmd",
args: [],
full: "yarn.cmd"
},
linux: { darwin: {
command: "yarn", command: "yarn",
args: [], args: [],
full: "yarn" 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: { spawnedNPM.stdout.on("data", (out) => {
command: "yarn", logger.custom("npm", out.toString().trim());
args: [], });
full: "yarn" default:
} logger.info(`Installing dependencies with ${packageManager}`);
} const spawnedAny = spawn(
} `${cmds[packageManager][platform()].command}`,
switch (packageManager) { cmds[packageManager][platform()].args,
case null: { cwd: workingDirectory }
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) => { spawnedAny.stdout.on("data", (out) => {
logger.custom("npm", out.toString().trim()) logger.custom(packageManager, 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) => { spawnedAny.stderr.on("data", (err) => {
logger.custom(packageManager, out.toString().trim()) 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() { 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) { if (NODE_VERSION! >= 12) {
logger.error(`Detected node ${NODE_VERSION}. At least node v12 required.`) logger.error(`Detected node ${NODE_VERSION}. At least node v12 required.`);
process.exit(1) process.exit(1);
} }
} }

View file

@ -5,83 +5,90 @@ import { copySync, removeSync } from "fs-extra";
import * as inquirer from "inquirer"; import * as inquirer from "inquirer";
import getPackageManager from "../lib/getPackageManager"; import getPackageManager from "../lib/getPackageManager";
import install from "../lib/installDependencies"; import install from "../lib/installDependencies";
import * as logger from "../utils/logger" import * as logger from "../utils/logger";
import constants from "../lib/constants" import constants from "../lib/constants";
import getConstant from "../lib/constants"; import getConstant from "../lib/constants";
import stream from "got"; import stream from "got";
import unzip from "unzip-stream"; import unzip from "unzip-stream";
import validateClient from "../lib/validateClient"; import validateClient from "../lib/validateClient";
const weclomeASCII = getConstant("welcomeMessage") const weclomeASCII = getConstant("welcomeMessage");
console.log(weclomeASCII) console.log(weclomeASCII);
inquirer inquirer
.prompt([ .prompt([
{ {
type: "input", type: "input",
name: "location", name: "location",
message: "Where should the project be initialized?" message: "Where should the project be initialized?",
}, },
{ {
type: 'list', type: "list",
name: 'flavor', name: "flavor",
message: 'Which flavor?', message: "Which flavor?",
choices: ['TypeScript', 'JavaScript'], choices: ["TypeScript", "JavaScript"],
filter(val) { filter(val) {
return val.toLowerCase(); return val.toLowerCase();
}, },
}, },
]) ])
.then((answers) => { .then((answers) => {
validateClient() validateClient();
mkdir(answers.location, (e) => { mkdir(answers.location, (e) => {
if (e && e.code != "EEXIST") { if (e && e.code != "EEXIST") {
logger.error("Failed to create project directory.") logger.error("Failed to create project directory.");
process.exit(1) process.exit(1);
} }
if (e) { if (e) {
if (e.code == "EEXIST") { if (e.code == "EEXIST") {
readdir(answers.location, (_, files) => { readdir(answers.location, (_, files) => {
if (files.length) { if (files.length) {
logger.error("Directory not empty.") logger.error("Directory not empty.");
process.exit(1) process.exit(1);
} }
}) });
} }
} }
}) });
let packageManager = getPackageManager() let packageManager = getPackageManager();
const start = async (TEMPLATE_DOWNLOAD_URL: string) => { 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", () => { download.on("finish", () => {
fs.createReadStream(`${answers.location}/create-guilded-bot_ts.zip`) fs.createReadStream(`${answers.location}/create-guilded-bot_ts.zip`)
.pipe(unzip.Extract({ path: `${answers.location}` })) .pipe(unzip.Extract({ path: `${answers.location}` }))
.on("finish", () => { .on("finish", () => {
removeSync(`${answers.location}/create-guilded-bot_ts.zip`) removeSync(`${answers.location}/create-guilded-bot_ts.zip`);
logger.success("🚀 Let's get started.") logger.success("🚀 Let's get started.");
}) });
}); });
}; };
if (answers.flavor == "typescript") { 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(() => { 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") { 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(() => { 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 progressStyle = kleur.bold().gray;
const successStyle = kleur.bold().green const successStyle = kleur.bold().green;
const errorStyle = kleur.black().bold().red const errorStyle = kleur.black().bold().red;
const warningStyle = kleur.black().bold().yellow const warningStyle = kleur.black().bold().yellow;
export function warn(log: string) { export function warn(log: string) {
console.log(warningStyle(`warning`), " ", log ) console.log(warningStyle(`warning`), " ", log);
} }
export function error(log: string) { export function error(log: string) {
console.log(errorStyle(`error`), " ", log ) console.log(errorStyle(`error`), " ", log);
} }
export function info(log: string) { export function info(log: string) {
console.log(successStyle(`info`), " ", log ) console.log(successStyle(`info`), " ", log);
} }
export function success(log: string) { export function success(log: string) {
console.log(successStyle(`success`), " ", log ) console.log(successStyle(`success`), " ", log);
} }
export function custom(customType: string, log: string) { export function custom(customType: string, log: string) {
console.log(progressStyle(`[${customType}] `), log) console.log(progressStyle(`[${customType}] `), log);
} }
export function customError(customType: string, log: string) { 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` # `📦framework`
This directory consists of the core frameworks for both JavaScript and TypeScript, including a shared `tsconfig.json`. This directory consists of the core frameworks for both JavaScript and TypeScript, including a shared `tsconfig.json`.
## Development ## 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. 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). 🚀 This is a guilded bot created using [create-guilded-bot](https://github.com/CompeyDev/create-guilded-bot).
## Getting Started ## Getting Started
In order to run the development environment, configure your .env file with the required variables and then execute the following commands: In order to run the development environment, configure your .env file with the required variables and then execute the following commands:
```bash ```bash
npm run dev npm run dev
# or with yarn # 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. 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 ## Learn More
Since create-guilded-bot uses guilded.js, you can learn more from their [official docs](https://guilded.js.org/). 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 :) ##### ✨ 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). 🚀 This is a guilded bot created using [create-guilded-bot](https://github.com/CompeyDev/create-guilded-bot).
## Getting Started ## Getting Started
In order to run the development environment, configure your .env file with the required variables and then execute the following commands: In order to run the development environment, configure your .env file with the required variables and then execute the following commands:
```bash ```bash
npm run dev npm run dev
# or with yarn # 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. 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 ## Learn More
Since create-guilded-bot uses guilded.js, you can learn more from their [official docs](https://guilded.js.org/). 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 :) ##### ✨ 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 { declare global {
namespace NodeJS { namespace NodeJS {
interface ProcessEnv { interface ProcessEnv {
botToken: string; botToken: string;
environment: "dev" | "prod" | "debug"; environment: "dev" | "prod" | "debug";
ownerId: string; ownerId: string;
botPrefix: string botPrefix: string;
}
} }
}
} }
export {}; export {};

View file

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

View file

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

View file

@ -1,6 +1,6 @@
import { client } from ".." import { client } from "..";
import { Event } from "../structures/Event" import { Event } from "../structures/Event";
export default new Event("ready", () => { 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(); export const client = new ExtendedClient();
client.start(); client.start();

View file

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

View file

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