https://github.com/mkvlrn/template-discordbot
An esm nodejs template for discord bots using discord.js
https://github.com/mkvlrn/template-discordbot
bot discord esm node template
Last synced: 3 months ago
JSON representation
An esm nodejs template for discord bots using discord.js
- Host: GitHub
- URL: https://github.com/mkvlrn/template-discordbot
- Owner: mkvlrn
- License: mit
- Created: 2024-10-30T05:58:51.000Z (over 1 year ago)
- Default Branch: main
- Last Pushed: 2026-04-14T07:38:50.000Z (3 months ago)
- Last Synced: 2026-04-14T09:30:02.420Z (3 months ago)
- Topics: bot, discord, esm, node, template
- Language: TypeScript
- Homepage:
- Size: 868 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# template-discordbot

[](https://github.com/mkvlrn/template-discordbot/generate)
[](https://mise.jdx.dev)

A sane, opinionated template for discord bots written in typescript using the [discord.js](https://discord.js.org/#/) library. It doesn't rely on transpilation - typescript is ran directly by node.
> [!NOTE]
> This template provides a [mise](https://mise.jdx.dev) configuration to make it easy to keep node and pnpm versions in sync.
Uses, among other tools/packages:
- [pnpm](https://github.com/pnpm/pnpm) as package manager for node
- [biome](https://github.com/biomejs/biome) for code linting and formatting
- [lefthook](https://github.com/evilmartians/lefthook) for git hooks
- [commitlint](https://github.com/conventional-changelog/commitlint) for commit message linting
- [vitest](https://github.com/vitest-dev/vitest) for testingypescript
- [envalid](https://github.com/af/envalid) for env validation and parsing
- [@mkvlrn/result](https://github.com/mkvlrn/tools/blob/main/packages/result/README.md) for error handling
## requirements and dependencies
If you use [mise](https://mise.jdx.dev) and run `mise install` in the project root, you'll have the correct node and pnpm versions installed.
This is _by far_ the easiest way to keep your environment consistent across different machines and team members, no matter the frequency of version updates. I'm not affiliated with mise but I wholeheartedly recommend it, so check it here: https://mise.jdx.dev.
If not using mise, make sure you have:
- node 24+ installed (v24.14.1 used)
- pnpm 10+ installed (v10.33.0 used)
Then, install dependencies with:
```bash
pnpm install
```
> [!NOTE]
> Git hooks are in place to make sure both the tooling managed by mise and the project dependencies are synced with each checkout and merge.
## subpath imports
Subpath imports (`#/`) are used instead of relative paths, mapped in both `package.json` and `tsconfig.json`.
**Example**:
```ts
import { add } from "#/math/basic"; // this points to ./src/math/basic.ts
```
## secrets
An untracked, local `.env` file can be used during development, and you can load it up with the `--env-file` flag for node.
Create a project there setting the following secrets:
- `DISCORD_CLIENT_ID`
- `DISCORD_CLIENT_TOKEN`
- `DEV_SERVER`
- `LOG_LEVEL`
The `dev`, `start`, `register`, and `unregister` npm scripts use the `.env` file by default, although you should probably use something else for secret management, such as [doppler](https://www.doppler.com/) or others.
This is just a low friction setup.
## running
### `pnpm dev`
Runs the project in watch mode.
### `pnpm start`
Runs the built project.
### `pnpm test`
Runs tests with vitest.
### `pnpm biome-fix`
Runs biome in fix mode to lint and format the project.
### `pnpm typecheck`
Runs type checking using tsc.
### `pnpm register [--dev]`
Registers slash commands globally, or to the dev server if `--dev` flag is provided
### `pnpm unregister [--dev]`
Unregisters slash commands globally, or from the dev server if `--dev` flag is provided
## adding or removing commands
Commands are **auto-loaded** from `./src/commands/`. Just create a file and call `createBotCommand`.
**Note:** Discord requires command names to be lowercase. Use kebab-case for multi-word commands (e.g., `my-command`).
1. Create a new file in `./src/commands/` (e.g., `my-command.ts`)
2. Call `createBotCommand` with your command definition:
```ts
import { SlashCommandBuilder } from "discord.js";
import { createBotCommand } from "#/modules/commands";
createBotCommand({
data: new SlashCommandBuilder().setName("my-command").setDescription("Does something"),
async execute(interaction) {
await interaction.reply("Hello!");
},
});
```
3. Run `pnpm register` to register commands globally (or `pnpm register --dev` for your dev server)
4. Restart your bot
### handling follow-up interactions
For commands with buttons, select menus, or modals, add a `followUp` handler. Use a prefix in `customId` to route interactions back to your command:
```ts
import { ActionRowBuilder, ButtonBuilder, ButtonStyle, SlashCommandBuilder } from "discord.js";
import { createBotCommand, type FollowUpInteraction } from "#/modules/commands";
createBotCommand({
data: new SlashCommandBuilder().setName("counter").setDescription("A simple counter"),
async execute(interaction) {
const button = new ButtonBuilder()
.setCustomId("counter:increment") // prefix must match command name
.setLabel("Click me")
.setStyle(ButtonStyle.Primary);
const row = new ActionRowBuilder().addComponents(button);
await interaction.reply({ content: "Count: 0", components: [row] });
},
async followUp(interaction: FollowUpInteraction) {
if (interaction.isButton()) {
await interaction.reply("Button clicked!");
}
},
});
```
## removing commands
1. Run `pnpm unregister` (or `pnpm unregister --dev`) to clean the slate
2. Delete the file from `./src/commands/`
3. Run `pnpm register` (or `pnpm register --dev`) to register commands again
4. Restart your bot
## example commands
The template includes several examples demonstrating different patterns:
| Command | Description |
| ------------ | ---------------------------------------------------- |
| `ping` | Simple reply |
| `roll` | Slash command with options (dropdown selection) |
| `roll-plus` | String input parsing with image generation |
| `roll-panel` | Interactive buttons and select menus with `followUp` |
## architecture
```bash
src/
├── commands/ # Drop command files here — auto-loaded
│ ├── ping.ts
│ ├── roll.ts
│ ├── roll-panel.ts
│ └── roll-plus.ts
├── modules/
│ ├── bot.ts # Client setup, login, graceful shutdown
│ ├── commands.ts # createBotCommand + auto-loader
│ ├── interaction.ts # Dispatches interactions to commands
│ └── logger.ts # Pino logger config
├── utils/ # Shared utilities (dice rolling, image gen)
└── main.ts # Entry point
```
## environment variables
Managed by [envalid](https://github.com/af/envalid) with full type safety:
| Variable | Description |
| ---------------------- | --------------------------------------------------------------------- |
| `DISCORD_CLIENT_ID` | Your Discord application's client ID |
| `DISCORD_CLIENT_TOKEN` | Your Discord bot token |
| `LOG_LEVEL` | Logging level (`trace`, `debug`, `info`, `warn`, `error`, `fatal`) |
| `DEV_SERVER`. | Your Discord test server (target of register/unregister with `--dev`) |
See `./src/env.ts` for the schema definition.
## ci
This repository uses GitHub Actions for CI. The workflow is defined in `.github/workflows/checks.yml`.
It automates:
- **Linting & Formatting**: Running Biome.
- **Type Checking**: Running TypeScript type checking.
- **Testing**: Running Vitest with code coverage (generated by Istanbul).
## vscode
You might want to install the recommended extensions in vscode. Search for **@recommended** in the extensions tab, they'll show up as _"workspace recommendations"_.
If you have been using eslint and prettier and their extensions, you might want to disable eslint entirely and keep prettier as the formatter only for certain types of files.
This is done by the `.vscode/settings.json` file.
Debug configuration is also included for running the source directly with node.
## license
MIT