feat(create-discord-bot): bun/deno templates (#9795)

This commit is contained in:
Noel
2023-08-21 22:48:13 +02:00
committed by GitHub
parent 8eb978d32c
commit dd5e7453e8
46 changed files with 700 additions and 115 deletions

View File

@@ -0,0 +1,23 @@
{
"name": "[REPLACE_ME]",
"version": "0.1.0",
"private": true,
"type": "module",
"scripts": {
"lint": "prettier --check . && eslint ./src --ext .[REPLACE_IMPORT_EXT] --format=pretty",
"deploy": "bun run src/util/deploy.[REPLACE_IMPORT_EXT]",
"format": "prettier --write . && eslint ./src --ext .[REPLACE_IMPORT_EXT] --fix --format=pretty",
"start": "bun run src/index.[REPLACE_IMPORT_EXT]"
},
"dependencies": {
"@discordjs/core": "^1.0.1",
"discord.js": "^14.13.0"
},
"devDependencies": {
"@sapphire/ts-config": "^4.0.1",
"eslint": "^8.47.0",
"eslint-config-neon": "^0.1.47",
"eslint-formatter-pretty": "^5.0.0",
"prettier": "^3.0.2"
}
}

View File

@@ -0,0 +1,25 @@
{
"name": "[REPLACE_ME]",
"version": "0.1.0",
"private": true,
"type": "module",
"scripts": {
"lint": "tsc && prettier --check . && eslint ./src --ext .[REPLACE_IMPORT_EXT] --format=pretty",
"deploy": "bun run src/util/deploy.[REPLACE_IMPORT_EXT]",
"format": "prettier --write . && eslint ./src --ext .[REPLACE_IMPORT_EXT] --fix --format=pretty",
"start": "bun run src/index.[REPLACE_IMPORT_EXT]"
},
"dependencies": {
"@discordjs/core": "^1.0.1",
"discord.js": "^14.13.0"
},
"devDependencies": {
"@sapphire/ts-config": "^4.0.1",
"bun-types": "^0.7.3",
"eslint": "^8.47.0",
"eslint-config-neon": "^0.1.47",
"eslint-formatter-pretty": "^5.0.0",
"prettier": "^3.0.2",
"typescript": "^5.1.6"
}
}

View File

@@ -0,0 +1,8 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"allowJs": true
},
"include": ["**/*.ts", "**/*.js", "**/*.test.ts", "**/*.test.js"],
"exclude": []
}

View File

@@ -0,0 +1,15 @@
{
"extends": "@sapphire/ts-config/extra-strict",
"compilerOptions": {
"declaration": false,
"declarationMap": false,
"module": "ESNext",
"moduleResolution": "Bundler",
"target": "ESNext",
"outDir": "dist",
"noEmit": true,
"allowImportingTsExtensions": true,
"types": ["bun-types"],
"skipLibCheck": true
}
}

View File

@@ -0,0 +1,2 @@
DISCORD_TOKEN=
APPLICATION_ID=

View File

@@ -0,0 +1,8 @@
{
"printWidth": 120,
"useTabs": true,
"singleQuote": true,
"quoteProps": "as-needed",
"trailingComma": "all",
"endOfLine": "lf"
}

View File

@@ -0,0 +1,3 @@
{
"recommendations": ["denoland.vscode-deno", "tamasfe.even-better-toml", "codezombiech.gitignore"]
}

View File

@@ -0,0 +1,15 @@
{
"editor.defaultFormatter": "denoland.vscode-deno",
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll": true,
"source.organizeImports": false
},
"editor.trimAutoWhitespace": false,
"files.insertFinalNewline": true,
"files.eol": "\n",
"npm.packageManager": "[REPLACE_ME]",
"deno.enable": "[REPLACE_BOOL]",
"deno.lint": "[REPLACE_BOOL]",
"deno.unstable": false
}

View File

@@ -0,0 +1,40 @@
{
"$schema": "https://raw.githubusercontent.com/denoland/deno/main/cli/schemas/config-file.v1.json",
"tasks": {
"lint": "deno lint",
"deploy": "deno run --allow-read --allow-env --allow-net src/util/deploy.ts",
"format": "deno fmt",
"start": "deno run --allow-read --allow-env --allow-net src/index.ts"
},
"lint": {
"include": ["src/"],
"rules": {
"tags": ["recommended"],
"exclude": ["require-await", "no-await-in-sync-fn"]
}
},
"fmt": {
"useTabs": true,
"lineWidth": 120,
"semiColons": true,
"singleQuote": true,
"proseWrap": "preserve",
"include": ["src/"]
},
"compilerOptions": {
"alwaysStrict": true,
"emitDecoratorMetadata": true,
"verbatimModuleSyntax": true,
"lib": ["deno.window"],
"noFallthroughCasesInSwitch": true,
"noImplicitReturns": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"removeComments": false,
"strict": true,
"allowUnreachableCode": false,
"allowUnusedLabels": false,
"exactOptionalPropertyTypes": false,
"noImplicitOverride": true
}
}

View File

@@ -0,0 +1,27 @@
import type { RESTPostAPIApplicationCommandsJSONBody, CommandInteraction } from 'npm:discord.js@^14.13.0';
import type { StructurePredicate } from '../util/loaders.ts';
/**
* Defines the structure of a command
*/
export type Command = {
/**
* The data for the command
*/
data: RESTPostAPIApplicationCommandsJSONBody;
/**
* The function to execute when the command is called
*
* @param interaction - The interaction of the command
*/
execute(interaction: CommandInteraction): Promise<void> | void;
};
// Defines the predicate to check if an object is a valid Command type
export const predicate: StructurePredicate<Command> = (structure): structure is Command =>
Boolean(structure) &&
typeof structure === 'object' &&
'data' in structure! &&
'execute' in structure &&
typeof structure.data === 'object' &&
typeof structure.execute === 'function';

View File

@@ -0,0 +1,11 @@
import type { Command } from './index.ts';
export default {
data: {
name: 'ping',
description: 'Ping!',
},
async execute(interaction) {
await interaction.reply('Pong!');
},
} satisfies Command;

View File

@@ -0,0 +1,33 @@
import type { ClientEvents } from 'npm:discord.js@^14.13.0';
import type { StructurePredicate } from '../util/loaders.ts';
/**
* Defines the structure of an event.
*/
export type Event<T extends keyof ClientEvents = keyof ClientEvents> = {
/**
* The function to execute when the event is emitted.
*
* @param parameters - The parameters of the event
*/
execute(...parameters: ClientEvents[T]): Promise<void> | void;
/**
* The name of the event to listen to
*/
name: T;
/**
* Whether or not the event should only be listened to once
*
* @defaultValue false
*/
once?: boolean;
};
// Defines the predicate to check if an object is a valid Event type.
export const predicate: StructurePredicate<Event> = (structure): structure is Event =>
Boolean(structure) &&
typeof structure === 'object' &&
'name' in structure! &&
'execute' in structure &&
typeof structure.name === 'string' &&
typeof structure.execute === 'function';

View File

@@ -0,0 +1,10 @@
import { Events } from 'npm:discord.js@^14.13.0';
import type { Event } from './index.ts';
export default {
name: Events.ClientReady,
once: true,
async execute(client) {
console.log(`Ready! Logged in as ${client.user.tag}`);
},
} satisfies Event<Events.ClientReady>;

View File

@@ -0,0 +1,18 @@
import 'https://deno.land/std@0.199.0/dotenv/load.ts';
import { URL } from 'node:url';
import { Client, GatewayIntentBits } from 'npm:discord.js@^14.13.0';
import { loadCommands, loadEvents } from './util/loaders.ts';
import { registerEvents } from './util/registerEvents.ts';
// Initialize the client
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
// Load the events and commands
const events = await loadEvents(new URL('events/', import.meta.url));
const commands = await loadCommands(new URL('commands/', import.meta.url));
// Register the event handlers
registerEvents(commands, events, client);
// Login to the client
void client.login(Deno.env.get('DISCORD_TOKEN'));

View File

@@ -0,0 +1,15 @@
import 'https://deno.land/std@0.199.0/dotenv/load.ts';
import { URL } from 'node:url';
import { API } from 'npm:@discordjs/core@^1.0.1/http-only';
import { REST } from 'npm:discord.js@^14.13.0';
import { loadCommands } from './loaders.ts';
const commands = await loadCommands(new URL('../commands/', import.meta.url));
const commandData = [...commands.values()].map((command) => command.data);
const rest = new REST({ version: '10' }).setToken(Deno.env.get('DISCORD_TOKEN')!);
const api = new API(rest);
const result = await api.applicationCommands.bulkOverwriteGlobalCommands(Deno.env.get('APPLICATION_ID')!, commandData);
console.log(`Successfully registered ${result.length} commands.`);

View File

@@ -0,0 +1,76 @@
import type { PathLike } from 'node:fs';
import { readdir, stat } from 'node:fs/promises';
import { URL } from 'node:url';
import type { Command } from '../commands/index.ts';
import { predicate as commandPredicate } from '../commands/index.ts';
import type { Event } from '../events/index.ts';
import { predicate as eventPredicate } from '../events/index.ts';
/**
* A predicate to check if the structure is valid
*/
export type StructurePredicate<T> = (structure: unknown) => structure is T;
/**
* Loads all the structures in the provided directory
*
* @param dir - The directory to load the structures from
* @param predicate - The predicate to check if the structure is valid
* @param recursive - Whether to recursively load the structures in the directory
* @returns
*/
export async function loadStructures<T>(
dir: PathLike,
predicate: StructurePredicate<T>,
recursive = true,
): Promise<T[]> {
// Get the stats of the directory
const statDir = await stat(dir);
// If the provided directory path is not a directory, throw an error
if (!statDir.isDirectory()) {
throw new Error(`The directory '${dir}' is not a directory.`);
}
// Get all the files in the directory
const files = await readdir(dir);
// Create an empty array to store the structures
const structures: T[] = [];
// Loop through all the files in the directory
for (const file of files) {
// If the file is index.js or the file does not end with .js, skip the file
if (file === 'index.ts' || !file.endsWith('.ts')) {
continue;
}
// Get the stats of the file
const statFile = await stat(new URL(`${dir}/${file}`));
// If the file is a directory and recursive is true, recursively load the structures in the directory
if (statFile.isDirectory() && recursive) {
structures.push(...(await loadStructures(`${dir}/${file}`, predicate, recursive)));
continue;
}
// Import the structure dynamically from the file
const structure = (await import(`${dir}/${file}`)).default;
// If the structure is a valid structure, add it
if (predicate(structure)) structures.push(structure);
}
return structures;
}
export async function loadCommands(dir: PathLike, recursive = true): Promise<Map<string, Command>> {
return (await loadStructures(dir, commandPredicate, recursive)).reduce(
(acc, cur) => acc.set(cur.data.name, cur),
new Map<string, Command>(),
);
}
export async function loadEvents(dir: PathLike, recursive = true): Promise<Event[]> {
return loadStructures(dir, eventPredicate, recursive);
}

View File

@@ -0,0 +1,25 @@
import { Events, type Client } from 'npm:discord.js@^14.13.0';
import type { Command } from '../commands/index.ts';
import type { Event } from '../events/index.ts';
export function registerEvents(commands: Map<string, Command>, events: Event[], client: Client): void {
// Create an event to handle command interactions
const interactionCreateEvent: Event<Events.InteractionCreate> = {
name: Events.InteractionCreate,
async execute(interaction) {
if (interaction.isCommand()) {
const command = commands.get(interaction.commandName);
if (!command) {
throw new Error(`Command '${interaction.commandName}' not found.`);
}
await command.execute(interaction);
}
},
};
for (const event of [...events, interactionCreateEvent]) {
client[event.once ? 'once' : 'on'](event.name, async (...args) => event.execute(...args));
}
}

View File

@@ -0,0 +1,10 @@
{
"recommendations": [
"esbenp.prettier-vscode",
"dbaeumer.vscode-eslint",
"tamasfe.even-better-toml",
"codezombiech.gitignore",
"christian-kohler.npm-intellisense",
"christian-kohler.path-intellisense"
]
}

View File

@@ -0,0 +1,13 @@
{
"eslint.validate": ["javascript", "javascriptreact", "typescript", "typescriptreact"],
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll": true,
"source.organizeImports": false
},
"editor.trimAutoWhitespace": false,
"files.insertFinalNewline": true,
"files.eol": "\n",
"npm.packageManager": "[REPLACE_ME]"
}

View File

@@ -1,5 +1,5 @@
{
"name": "[REPLACE-NAME]",
"name": "[REPLACE_ME]",
"version": "0.1.0",
"private": true,
"type": "module",
@@ -10,14 +10,14 @@
"deploy": "node --require dotenv/config src/util/deploy.js"
},
"dependencies": {
"@discordjs/core": "^0.6.0",
"discord.js": "^14.11.0",
"dotenv": "^16.0.3"
"@discordjs/core": "^1.0.1",
"discord.js": "^14.13.0",
"dotenv": "^16.3.1"
},
"devDependencies": {
"eslint": "^8.40.0",
"eslint": "^8.47.0",
"eslint-config-neon": "^0.1.47",
"eslint-formatter-pretty": "^5.0.0",
"prettier": "^2.8.8"
"prettier": "^3.0.2"
}
}

View File

@@ -1,3 +1,4 @@
import process from 'node:process';
import { URL } from 'node:url';
import { Client, GatewayIntentBits } from 'discord.js';
import { loadCommands, loadEvents } from './util/loaders.js';
@@ -14,4 +15,4 @@ const commands = await loadCommands(new URL('commands/', import.meta.url));
registerEvents(commands, events, client);
// Login to the client
void client.login();
void client.login(process.env.DISCORD_TOKEN);

View File

@@ -4,10 +4,10 @@ import { API } from '@discordjs/core/http-only';
import { REST } from 'discord.js';
import { loadCommands } from './loaders.js';
const commands = await loadCommands(new URL('commands/', import.meta.url));
const commands = await loadCommands(new URL('../commands/', import.meta.url));
const commandData = [...commands.values()].map((command) => command.data);
const rest = new REST({ version: '10' }).setToken(process.env.TOKEN);
const rest = new REST({ version: '10' }).setToken(process.env.DISCORD_TOKEN);
const api = new API(rest);
const result = await api.applicationCommands.bulkOverwriteGlobalCommands(process.env.APPLICATION_ID, commandData);

View File

@@ -0,0 +1,10 @@
{
"recommendations": [
"esbenp.prettier-vscode",
"dbaeumer.vscode-eslint",
"tamasfe.even-better-toml",
"codezombiech.gitignore",
"christian-kohler.npm-intellisense",
"christian-kohler.path-intellisense"
]
}

View File

@@ -0,0 +1,13 @@
{
"eslint.validate": ["javascript", "javascriptreact", "typescript", "typescriptreact"],
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll": true,
"source.organizeImports": false
},
"editor.trimAutoWhitespace": false,
"files.insertFinalNewline": true,
"files.eol": "\n",
"npm.packageManager": "[REPLACE_ME]"
}

View File

@@ -1,27 +1,27 @@
{
"name": "[REPLACE-NAME]",
"name": "[REPLACE_ME]",
"version": "0.1.0",
"private": true,
"type": "module",
"scripts": {
"test": "tsc",
"build": "tsc",
"lint": "prettier --check . && eslint ./src --ext .ts --format=pretty",
"deploy": "node --require dotenv/config dist/util/deploy.js",
"format": "prettier --write . && eslint ./src --ext .ts --fix --format=pretty",
"start": "node --require dotenv/config dist/index.js"
},
"dependencies": {
"@discordjs/core": "^0.6.0",
"discord.js": "^14.11.0",
"dotenv": "^16.0.3"
"@discordjs/core": "^1.0.1",
"discord.js": "^14.13.0",
"dotenv": "^16.3.1"
},
"devDependencies": {
"@sapphire/ts-config": "^4.0.0",
"@types/node": "^18.15.3",
"eslint": "^8.40.0",
"@sapphire/ts-config": "^4.0.1",
"@types/node": "^18.17.6",
"eslint": "^8.47.0",
"eslint-config-neon": "^0.1.47",
"eslint-formatter-pretty": "^5.0.0",
"prettier": "^2.8.8",
"typescript": "^5.0.4"
"prettier": "^3.0.2",
"typescript": "^5.1.6"
}
}

View File

@@ -1,5 +1,5 @@
import type { RESTPostAPIApplicationCommandsJSONBody, CommandInteraction } from 'discord.js';
import type { StructurePredicate } from '../util/loaders.js';
import type { StructurePredicate } from '../util/loaders.[REPLACE_IMPORT_EXT]';
/**
* Defines the structure of a command

View File

@@ -1,4 +1,4 @@
import type { Command } from './index.js';
import type { Command } from './index.[REPLACE_IMPORT_EXT]';
export default {
data: {

View File

@@ -1,5 +1,5 @@
import type { ClientEvents } from 'discord.js';
import type { StructurePredicate } from '../util/loaders.js';
import type { StructurePredicate } from '../util/loaders.[REPLACE_IMPORT_EXT]';
/**
* Defines the structure of an event.

View File

@@ -1,5 +1,5 @@
import { Events } from 'discord.js';
import type { Event } from './index.js';
import type { Event } from './index.[REPLACE_IMPORT_EXT]';
export default {
name: Events.ClientReady,
@@ -7,4 +7,4 @@ export default {
async execute(client) {
console.log(`Ready! Logged in as ${client.user.tag}`);
},
} satisfies Event<'ready'>;
} satisfies Event<Events.ClientReady>;

View File

@@ -1,7 +1,8 @@
import process from 'node:process';
import { URL } from 'node:url';
import { Client, GatewayIntentBits } from 'discord.js';
import { loadCommands, loadEvents } from './util/loaders.js';
import { registerEvents } from './util/registerEvents.js';
import { loadCommands, loadEvents } from './util/loaders.[REPLACE_IMPORT_EXT]';
import { registerEvents } from './util/registerEvents.[REPLACE_IMPORT_EXT]';
// Initialize the client
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
@@ -14,4 +15,4 @@ const commands = await loadCommands(new URL('commands/', import.meta.url));
registerEvents(commands, events, client);
// Login to the client
void client.login();
void client.login(process.env.DISCORD_TOKEN);

View File

@@ -2,12 +2,12 @@ import process from 'node:process';
import { URL } from 'node:url';
import { API } from '@discordjs/core/http-only';
import { REST } from 'discord.js';
import { loadCommands } from './loaders.js';
import { loadCommands } from './loaders.[REPLACE_IMPORT_EXT]';
const commands = await loadCommands(new URL('commands/', import.meta.url));
const commands = await loadCommands(new URL('../commands/', import.meta.url));
const commandData = [...commands.values()].map((command) => command.data);
const rest = new REST({ version: '10' }).setToken(process.env.TOKEN!);
const rest = new REST({ version: '10' }).setToken(process.env.DISCORD_TOKEN!);
const api = new API(rest);
const result = await api.applicationCommands.bulkOverwriteGlobalCommands(process.env.APPLICATION_ID!, commandData);

View File

@@ -1,10 +1,10 @@
import type { PathLike } from 'node:fs';
import { readdir, stat } from 'node:fs/promises';
import { URL } from 'node:url';
import type { Command } from '../commands/index.js';
import { predicate as commandPredicate } from '../commands/index.js';
import type { Event } from '../events/index.js';
import { predicate as eventPredicate } from '../events/index.js';
import type { Command } from '../commands/index.[REPLACE_IMPORT_EXT]';
import { predicate as commandPredicate } from '../commands/index.[REPLACE_IMPORT_EXT]';
import type { Event } from '../events/index.[REPLACE_IMPORT_EXT]';
import { predicate as eventPredicate } from '../events/index.[REPLACE_IMPORT_EXT]';
/**
* A predicate to check if the structure is valid
@@ -40,8 +40,8 @@ export async function loadStructures<T>(
// Loop through all the files in the directory
for (const file of files) {
// If the file is index.js or the file does not end with .js, skip the file
if (file === 'index.js' || !file.endsWith('.js')) {
// If the file is index.[REPLACE_IMPORT_EXT] or the file does not end with .[REPLACE_IMPORT_EXT], skip the file
if (file === 'index.[REPLACE_IMPORT_EXT]' || !file.endsWith('.[REPLACE_IMPORT_EXT]')) {
continue;
}

View File

@@ -1,6 +1,6 @@
import { Events, type Client } from 'discord.js';
import type { Command } from '../commands/index.js';
import type { Event } from '../events/index.js';
import type { Command } from '../commands/index.[REPLACE_IMPORT_EXT]';
import type { Event } from '../events/index.[REPLACE_IMPORT_EXT]';
export function registerEvents(commands: Map<string, Command>, events: Event[], client: Client): void {
// Create an event to handle command interactions

View File

@@ -6,6 +6,7 @@
"module": "ESNext",
"moduleResolution": "NodeNext",
"target": "ESNext",
"outDir": "dist"
"outDir": "dist",
"skipLibCheck": true
}
}