-
Notifications
You must be signed in to change notification settings - Fork 2.3k
feat/typescript: add TypeScript examples to the guide #1560
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
omar-sobhy
wants to merge
9
commits into
discordjs:main
Choose a base branch
from
omar-sobhy:feat/typescript
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from 3 commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
d6676dc
Add TypeScript Examples
omar-sobhy 70cdde9
fix(popular-topics): replace deprecated `underscore` with `underline`…
sdanialraza d524703
Merge branch 'discordjs:main' into feat/typescript
omar-sobhy 5b9615e
add node: prefix to node modules in code examples
omar-sobhy c9a7731
WIP: Add TypeScript-specific cooldown information
omar-sobhy 5c671cd
WIP: Add trailing comma
omar-sobhy c7ff4c8
Merge branch 'discordjs:main' into feat/typescript
omar-sobhy c35371d
WIP: delete unused file
omar-sobhy edda949
WIP: Add typescript-eslint information
omar-sobhy File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
|
@@ -39,10 +39,16 @@ Add two more properties to your `config.json` file, which we'll need in the depl | |||||
} | ||||||
``` | ||||||
|
||||||
::: typescript-tip | ||||||
Don't forget to update `src/types/Config.ts` and add the additional properties to the type declaration. | ||||||
::: | ||||||
|
||||||
With these defined, you can use the deployment script below: | ||||||
|
||||||
<!-- eslint-skip --> | ||||||
|
||||||
:::: code-group | ||||||
::: code-group-item js | ||||||
```js | ||||||
const { REST, Routes } = require('discord.js'); | ||||||
const { clientId, guildId, token } = require('./config.json'); | ||||||
|
@@ -91,6 +97,65 @@ const rest = new REST().setToken(token); | |||||
} | ||||||
})(); | ||||||
``` | ||||||
::: | ||||||
::: code-group-item ts | ||||||
```ts | ||||||
import { REST, Routes } from 'discord.js'; | ||||||
import { Config, assertObjectIsConfig } from './types/Config'; | ||||||
import fs from 'fs'; | ||||||
import path from 'path'; | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
|
||||||
const configRaw = fs.readFileSync('./config.json', { encoding: 'utf-8' }); | ||||||
const config = JSON.parse(configRaw); | ||||||
|
||||||
assertObjectIsConfig(config); | ||||||
|
||||||
const { clientId, guildId, token } = config; | ||||||
|
||||||
(async () => { | ||||||
const commands = []; | ||||||
// Grab all the command folders from the commands directory you created earlier | ||||||
const foldersPath = path.join(__dirname, 'commands'); | ||||||
const commandFolders = fs.readdirSync(foldersPath); | ||||||
|
||||||
for (const folder of commandFolders) { | ||||||
// Grab all the command files from the commands directory you created earlier | ||||||
const commandsPath = path.join(foldersPath, folder); | ||||||
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js')); | ||||||
// Grab the SlashCommandBuilder#toJSON() output of each command's data for deployment | ||||||
for (const file of commandFiles) { | ||||||
const filePath = path.join(commandsPath, file); | ||||||
const { default: command } = await import(filePath); | ||||||
if ('data' in command && 'execute' in command) { | ||||||
commands.push(command.data.toJSON()); | ||||||
} else { | ||||||
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`); | ||||||
} | ||||||
} | ||||||
} | ||||||
|
||||||
// Construct and prepare an instance of the REST module | ||||||
const rest = new REST().setToken(token); | ||||||
|
||||||
// and deploy your commands! | ||||||
try { | ||||||
console.log(`Started refreshing ${commands.length} application (/) commands.`); | ||||||
|
||||||
// The put method is used to fully refresh all commands in the guild with the current set | ||||||
const data = await rest.put( | ||||||
Routes.applicationGuildCommands(clientId, guildId), | ||||||
{ body: commands }, | ||||||
); | ||||||
|
||||||
console.log(`Successfully reloaded ${data.length} application (/) commands.`); | ||||||
} catch (error) { | ||||||
// And of course, make sure you catch and log any errors! | ||||||
console.error(error); | ||||||
} | ||||||
})(); | ||||||
``` | ||||||
::: | ||||||
:::: | ||||||
|
||||||
Once you fill in these values, run `node deploy-commands.js` in your project directory to register your commands to the guild specified. If you see the success message, check for the commands in the server by typing `/`! If all goes well, you should be able to run them and see your bot's response in Discord! | ||||||
|
||||||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
|
@@ -18,8 +18,32 @@ This page details how to complete **Step 2**. Make sure to also complete the oth | |||||
|
||||||
Now that your command files have been created, your bot needs to load these files on startup. | ||||||
|
||||||
In your `index.js` file, make these additions to the base template: | ||||||
In your `index.js` or `index.ts` file, make these additions to the base template: | ||||||
|
||||||
::::: typescript-tip | ||||||
TypeScript will not let you attach a `commands` property to your client instance without some work. We'll need to extend the base `Client` class and create our own `ExtendedClient` class with the additional properties we need. | ||||||
|
||||||
Add the following file: | ||||||
:::: code-group | ||||||
::: code-group-item src/structures/ExtendedClient.ts | ||||||
```ts | ||||||
import { Client, ClientOptions, Collection } from 'discord.js'; | ||||||
import { SlashCommand } from '../types/SlashCommand'; | ||||||
|
||||||
export class ExtendedClient extends Client { | ||||||
constructor(options: ClientOptions, public commands: Collection<string, SlashCommand> = new Collection()) { | ||||||
super(options); | ||||||
} | ||||||
} | ||||||
``` | ||||||
|
||||||
This class can be instantiated just like the `Client` class, except it also accepts a second `commands` parameter. This parameter will default to an empty `Collection` if nothing is passed as an argument. | ||||||
::: | ||||||
:::: | ||||||
::::: | ||||||
|
||||||
:::: code-group | ||||||
::: code-group-item js | ||||||
```js {1-3,8} | ||||||
const fs = require('node:fs'); | ||||||
const path = require('node:path'); | ||||||
|
@@ -30,8 +54,31 @@ const client = new Client({ intents: [GatewayIntentBits.Guilds] }); | |||||
|
||||||
client.commands = new Collection(); | ||||||
``` | ||||||
::: | ||||||
:::code-group-item ts | ||||||
```ts {1-2} | ||||||
import { readFileSync } from 'fs'; | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
import path from 'path'; | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
import { Client, Events, GatewayIntentBits } from 'discord.js'; | ||||||
import { ExtendedClient } from './structures/ExtendedClient'; | ||||||
import { Config, assertObjectIsConfig } from './types/Config'; | ||||||
|
||||||
// Read the config file | ||||||
const configRaw = fs.readFileSync('../config.json', { encoding: 'utf-8' }); | ||||||
const config = JSON.parse(configRaw); | ||||||
|
||||||
assertObjectIsConfig(config); | ||||||
|
||||||
|
||||||
const { token } = config; | ||||||
|
||||||
// ExtendedClient's second `commands` parameter defaults to an empty Collection | ||||||
const client = new ExtendedClient({ intents: [GatewayIntentBits.Guilds] }); | ||||||
``` | ||||||
::: | ||||||
:::: | ||||||
|
||||||
We recommend attaching a `.commands` property to your client instance so that you can access your commands in other files. The rest of the examples in this guide will follow this convention. For TypeScript users, we recommend extending the base Client class to add this property, [casting](https://www.typescripttutorial.net/typescript-tutorial/type-casting/), or [augmenting the module type](https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation). | ||||||
We recommend attaching a `.commands` property to your client instance so that you can access your commands in other files. The rest of the examples in this guide will follow this convention. | ||||||
|
||||||
::: tip | ||||||
- The [`fs`](https://nodejs.org/api/fs.html) module is Node's native file system module. `fs` is used to read the `commands` directory and identify our command files. | ||||||
|
@@ -41,6 +88,8 @@ We recommend attaching a `.commands` property to your client instance so that yo | |||||
|
||||||
Next, using the modules imported above, dynamically retrieve your command files with a few more additions to the `index.js` file: | ||||||
|
||||||
:::: code-group | ||||||
::: code-group-item js | ||||||
```js {3-19} | ||||||
client.commands = new Collection(); | ||||||
|
||||||
|
@@ -62,6 +111,36 @@ for (const folder of commandFolders) { | |||||
} | ||||||
} | ||||||
``` | ||||||
::: | ||||||
::: code-group-item ts | ||||||
```ts {3-19} | ||||||
const foldersPath = path.join(__dirname, '../build/commands'); | ||||||
const commandFolders = fs.readdirSync(foldersPath); | ||||||
|
||||||
for (const folder of commandFolders) { | ||||||
const commandsPath = path.join(foldersPath, folder); | ||||||
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js')); | ||||||
for (const file of commandFiles) { | ||||||
const filePath = path.join(commandsPath, file); | ||||||
import(filePath).then(module => { | ||||||
const command = module.default; | ||||||
// Set a new item in the Collection with the key as the command name and the value as the exported module | ||||||
if ('data' in command && 'execute' in command) { | ||||||
client.commands.set(command.data.name, command); | ||||||
} else { | ||||||
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`); | ||||||
} | ||||||
}); | ||||||
} | ||||||
} | ||||||
|
||||||
``` | ||||||
::: | ||||||
:::: | ||||||
|
||||||
::: typescript-tip | ||||||
The code above may require slight modifications depending on your `tsconfig.json`. In particular, if the `module` option is changed from the default `commonjs` value to one of the ESM values, you will need to change the `filePath` inside the `import()` call, as ESM does not support importing modules from absolute paths without a `file:///` prefix. You will also need to use `import.meta.dirname` instead of `__dirname`. Your mileage may vary! | ||||||
::: | ||||||
|
||||||
First, [`path.join()`](https://nodejs.org/api/path.html) helps to construct a path to the `commands` directory. The first [`fs.readdirSync()`](https://nodejs.org/api/fs.html#fs_fs_readdirsync_path_options) method then reads the path to the directory and returns an array of all the folder names it contains, currently `['utility']`. The second `fs.readdirSync()` method reads the path to this directory and returns an array of all the file names they contain, currently `['ping.js', 'server.js', 'user.js']`. To ensure only command files get processed, `Array.filter()` removes any non-JavaScript files from the array. | ||||||
|
||||||
|
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.