Compare commits
325 Commits
@discordjs
...
@discordjs
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d04987f09b | ||
|
|
ca5a2626b4 | ||
|
|
3c5a4dc7a7 | ||
|
|
447652ec8a | ||
|
|
488aa58b29 | ||
|
|
a92d19212d | ||
|
|
fd8197fe5b | ||
|
|
8f4256db8a | ||
|
|
6307f81385 | ||
|
|
d26e022afc | ||
|
|
afa98793cd | ||
|
|
386f206caf | ||
|
|
351a18bc35 | ||
|
|
84f1b1890d | ||
|
|
e5effb6f6a | ||
|
|
125405f1cf | ||
|
|
bc83cabfda | ||
|
|
20268ac0c4 | ||
|
|
3c85fb21e6 | ||
|
|
4141405dcd | ||
|
|
8c782bfd52 | ||
|
|
8d97017458 | ||
|
|
ceab07bec8 | ||
|
|
7fb91c57f7 | ||
|
|
09b0382c45 | ||
|
|
719e54a921 | ||
|
|
ede9f4e5e2 | ||
|
|
df40dcdb85 | ||
|
|
53c17e00c0 | ||
|
|
dc73c938ff | ||
|
|
a48d0efb09 | ||
|
|
a73d54e43a | ||
|
|
cf8012c200 | ||
|
|
0803eb562b | ||
|
|
78381a56cf | ||
|
|
6d5840c61e | ||
|
|
75d91b52b3 | ||
|
|
766be94b93 | ||
|
|
b61e4fb0dc | ||
|
|
d64330a157 | ||
|
|
2818d7cc1d | ||
|
|
a6dbe163dd | ||
|
|
73c2f8aa17 | ||
|
|
a873ec1e85 | ||
|
|
db925fa269 | ||
|
|
8f3bd38072 | ||
|
|
8f014c65ef | ||
|
|
1716202f44 | ||
|
|
1cab79f6fd | ||
|
|
7b494aca5b | ||
|
|
cd6986854f | ||
|
|
6c2242f4f9 | ||
|
|
75308f2669 | ||
|
|
bc2798b8ee | ||
|
|
a531dc9f1c | ||
|
|
911e6eff75 | ||
|
|
1ab60f9da4 | ||
|
|
df8b6e9934 | ||
|
|
24a61495b9 | ||
|
|
e1b6eeed0e | ||
|
|
53aa24d418 | ||
|
|
9b06734445 | ||
|
|
9345d1b1ac | ||
|
|
47843493a5 | ||
|
|
6c7a5ed1e7 | ||
|
|
985def3f25 | ||
|
|
1c4a12c7d6 | ||
|
|
8107c5c0e7 | ||
|
|
b85a3f2dde | ||
|
|
3535321b98 | ||
|
|
46167a79d7 | ||
|
|
cffa5d19c9 | ||
|
|
5d6eed6414 | ||
|
|
90e243d350 | ||
|
|
590f5bc38e | ||
|
|
7196fe36e8 | ||
|
|
5351ab429b | ||
|
|
d033f925e0 | ||
|
|
13073acefc | ||
|
|
7c8849fae5 | ||
|
|
d01e8aa8af | ||
|
|
4dcc9c50f8 | ||
|
|
a51c48e743 | ||
|
|
1edd01a7a4 | ||
|
|
7b617bd22e | ||
|
|
0c175c02e9 | ||
|
|
460ac7dfe2 | ||
|
|
64324a8be1 | ||
|
|
b6162bc5b5 | ||
|
|
280ed0ce08 | ||
|
|
5b8d535fd6 | ||
|
|
c4a3120354 | ||
|
|
8482e3c95d | ||
|
|
12482b70ed | ||
|
|
fa746b079d | ||
|
|
fc3f0756a4 | ||
|
|
3bfb6197a0 | ||
|
|
5ecc4f13b5 | ||
|
|
f83a8a58c9 | ||
|
|
9ddb3ff71d | ||
|
|
7ce6bb99e9 | ||
|
|
da6de92e8c | ||
|
|
bbf80efbb0 | ||
|
|
227232112d | ||
|
|
37181ab232 | ||
|
|
cdaa0a36f5 | ||
|
|
fc5b9c523b | ||
|
|
256b68bf9f | ||
|
|
75195cc539 | ||
|
|
8d5ce32080 | ||
|
|
5bfcf93e29 | ||
|
|
28f51791a2 | ||
|
|
e6274681fd | ||
|
|
00da44a120 | ||
|
|
ab39683a50 | ||
|
|
3e80f0b384 | ||
|
|
e53b94c979 | ||
|
|
6b2c3fb9d0 | ||
|
|
d8d21cf370 | ||
|
|
8e9a2b4630 | ||
|
|
d4f12e0a0c | ||
|
|
d7b18f0681 | ||
|
|
166c961261 | ||
|
|
506f7fcd3b | ||
|
|
51d53f5117 | ||
|
|
aa32d67619 | ||
|
|
4b077e679c | ||
|
|
c190c57d64 | ||
|
|
423bfce286 | ||
|
|
5d05b7230a | ||
|
|
7e875f6919 | ||
|
|
c429763be8 | ||
|
|
1b7981e469 | ||
|
|
f2ad0762c5 | ||
|
|
6d7f3b0f5c | ||
|
|
201b002ad4 | ||
|
|
b327f4925f | ||
|
|
e262df9117 | ||
|
|
7a761d4cfb | ||
|
|
ac9bf3ac06 | ||
|
|
133a6bbf49 | ||
|
|
63fc9f8504 | ||
|
|
a9f2bff82a | ||
|
|
54ceedf6c5 | ||
|
|
36b7fb2f00 | ||
|
|
9a56edaf8c | ||
|
|
be81c8bf3b | ||
|
|
c77a1765c4 | ||
|
|
3665ad65d0 | ||
|
|
d4de1cd09e | ||
|
|
481bbc924f | ||
|
|
ca81e61b4c | ||
|
|
eb603c0d11 | ||
|
|
072c9da5df | ||
|
|
cd591327d6 | ||
|
|
71e67d8c97 | ||
|
|
a9e0de4288 | ||
|
|
c5b4423a5a | ||
|
|
47b08be509 | ||
|
|
2e0804ae92 | ||
|
|
71983cc5d1 | ||
|
|
0f3d870ce6 | ||
|
|
ce4e1fc2c6 | ||
|
|
0762ddb3f4 | ||
|
|
80af9696d3 | ||
|
|
48cab844d4 | ||
|
|
8b71f44b1f | ||
|
|
f27631175a | ||
|
|
ad217cc760 | ||
|
|
1ba7394a7d | ||
|
|
260c46d51c | ||
|
|
6229597db2 | ||
|
|
8d212e4859 | ||
|
|
51e8f02ef7 | ||
|
|
496c4e2884 | ||
|
|
77191a2e7b | ||
|
|
375483b0f9 | ||
|
|
17cd4b610a | ||
|
|
988f8c7546 | ||
|
|
217e5d8100 | ||
|
|
40d07fbbbd | ||
|
|
1b15d31b5a | ||
|
|
d26df5faba | ||
|
|
78fe247fc4 | ||
|
|
36216c0e1a | ||
|
|
6212bffa30 | ||
|
|
b2e1bb92d0 | ||
|
|
2e09cb4c1f | ||
|
|
1b4d34cebf | ||
|
|
8153ca99ee | ||
|
|
43e205b840 | ||
|
|
c6ca5a83e7 | ||
|
|
5c52bb9590 | ||
|
|
a49ed0a2d5 | ||
|
|
3e01f91bbb | ||
|
|
7d341000d4 | ||
|
|
b49c5c9f48 | ||
|
|
ce287f21d1 | ||
|
|
d6bca9bb4d | ||
|
|
a2ab2b8717 | ||
|
|
ecd1b5da11 | ||
|
|
0eb866357b | ||
|
|
d2d27ce734 | ||
|
|
603446a692 | ||
|
|
f1fdd5b010 | ||
|
|
5d1a4c27d5 | ||
|
|
98a76db482 | ||
|
|
516c46117c | ||
|
|
7d7972d239 | ||
|
|
7b10e8cb63 | ||
|
|
2f18323d2c | ||
|
|
e04801bba1 | ||
|
|
09a9fb57e0 | ||
|
|
025b7aea29 | ||
|
|
7aa5ea731f | ||
|
|
f883279ab3 | ||
|
|
f1b2dec8e1 | ||
|
|
0a1701b046 | ||
|
|
5dcc6df224 | ||
|
|
1c35425120 | ||
|
|
cf1f5c0f0c | ||
|
|
a210fc64a2 | ||
|
|
24f17998c8 | ||
|
|
eda118dae9 | ||
|
|
f2fce0a7da | ||
|
|
29389e39f4 | ||
|
|
d5e9e36e8a | ||
|
|
8c0eb56ba5 | ||
|
|
1b74c774c0 | ||
|
|
01949d6e3a | ||
|
|
3ea26cc1a6 | ||
|
|
a516d46f91 | ||
|
|
b35b935679 | ||
|
|
0928c8f6ff | ||
|
|
188d5eea28 | ||
|
|
412e4fffae | ||
|
|
5e2f94c591 | ||
|
|
49627b1f46 | ||
|
|
bcb48fea3e | ||
|
|
c87e826087 | ||
|
|
2dddbe1f32 | ||
|
|
86e5f5a119 | ||
|
|
300059cb26 | ||
|
|
d4c1fecbe2 | ||
|
|
79bcdfa767 | ||
|
|
ca4de2d9c6 | ||
|
|
794abe8450 | ||
|
|
02dfaf1aa2 | ||
|
|
cac3c07729 | ||
|
|
83143178aa | ||
|
|
615752e32b | ||
|
|
2c25639a85 | ||
|
|
a76c1ddacc | ||
|
|
0d0e4d1cb6 | ||
|
|
d35f670d7a | ||
|
|
e4c5f794b0 | ||
|
|
88cab1a0ec | ||
|
|
1c2cc09e05 | ||
|
|
2a684361d4 | ||
|
|
66dc4014fe | ||
|
|
39c6694561 | ||
|
|
70da3746f8 | ||
|
|
0340622f1a | ||
|
|
f36878677c | ||
|
|
e5859b41cf | ||
|
|
8218ffc78d | ||
|
|
7ff3d528d9 | ||
|
|
0b7f296b62 | ||
|
|
85a379fdf8 | ||
|
|
8ffcf77840 | ||
|
|
fcb3a1ab27 | ||
|
|
40be4f80dc | ||
|
|
ee907f32f3 | ||
|
|
731ea5f3cb | ||
|
|
24c462bf6f | ||
|
|
78e02c4b63 | ||
|
|
dcf8757d35 | ||
|
|
a0c57abadd | ||
|
|
1c5a6fa552 | ||
|
|
6a221a9676 | ||
|
|
dcf58d8140 | ||
|
|
676307ff5c | ||
|
|
23e0ac56f4 | ||
|
|
8073561824 | ||
|
|
c0f2dd7131 | ||
|
|
d6905b3b97 | ||
|
|
774e23c572 | ||
|
|
1c8567f147 | ||
|
|
733c96c255 | ||
|
|
69cdeb7296 | ||
|
|
0019700869 | ||
|
|
3ea4d26ee9 | ||
|
|
250eccf118 | ||
|
|
7d3827ebd1 | ||
|
|
d1955f7c9e | ||
|
|
6412da4921 | ||
|
|
79123fb260 | ||
|
|
3d2f4b405e | ||
|
|
bfee6c8d88 | ||
|
|
fbbce3eb4b | ||
|
|
b2eec5f9fc | ||
|
|
b618e215f2 | ||
|
|
d66d113333 | ||
|
|
1b9d07f941 | ||
|
|
f893c6a357 | ||
|
|
687bbd889f | ||
|
|
f195556b64 | ||
|
|
9aafdd6214 | ||
|
|
e3e7d500dc | ||
|
|
3615e2f2d2 | ||
|
|
a7425c29c4 | ||
|
|
c519fe66c9 | ||
|
|
24f280290b | ||
|
|
6912faa9b3 | ||
|
|
0645bf0f7f | ||
|
|
6aba9e99eb | ||
|
|
5efdf57894 | ||
|
|
74059c9d97 | ||
|
|
8d345a041e | ||
|
|
1cbd04e8fd | ||
|
|
8592edba39 | ||
|
|
38f0986000 | ||
|
|
9e077b749c | ||
|
|
b977ba5f4d | ||
|
|
1a6db13f6f |
@@ -1,31 +1,33 @@
|
||||
# Packages
|
||||
node_modules/
|
||||
**/node_modules
|
||||
|
||||
# Log files
|
||||
logs/
|
||||
*.log
|
||||
npm-debug.log*
|
||||
**/logs
|
||||
**/*.log
|
||||
**/npm-debug.log*
|
||||
|
||||
# Runtime data
|
||||
pids
|
||||
*.pid
|
||||
*.seed
|
||||
**/pids
|
||||
**/*.pid
|
||||
**/*.seed
|
||||
|
||||
# Env
|
||||
.env
|
||||
**/.env
|
||||
|
||||
# Dist
|
||||
dist/
|
||||
**/dist/
|
||||
**/dist-docs/
|
||||
|
||||
# Miscellaneous
|
||||
.tmp/
|
||||
.vscode/*
|
||||
.idea/
|
||||
.DS_Store
|
||||
.turbo
|
||||
tsconfig.tsbuildinfo
|
||||
coverage/
|
||||
__tests__/
|
||||
**/.tmp
|
||||
**/.vscode
|
||||
**/.idea
|
||||
**/.DS_Store
|
||||
**/.turbo
|
||||
**/tsconfig.tsbuildinfo
|
||||
**/coverage
|
||||
**/__tests__
|
||||
**/out
|
||||
|
||||
# yarn
|
||||
.pnp.*
|
||||
@@ -37,20 +39,29 @@ __tests__/
|
||||
!.yarn/versions
|
||||
|
||||
# Cache
|
||||
.prettiercache
|
||||
.eslintcache
|
||||
**/.prettiercache
|
||||
**/.eslintcache
|
||||
**/.vercel
|
||||
|
||||
# Docker specific
|
||||
.cliff-jumperrc.json
|
||||
api-extractor.json
|
||||
.eslintrc.json
|
||||
.lintstagedrc.cjs
|
||||
.lintstagedrc.cjs
|
||||
.prettierignore
|
||||
.prettierrc.js
|
||||
.prettierrc.cjs
|
||||
cliff.toml
|
||||
CHANGELOG.md
|
||||
README.md
|
||||
tsconfig.eslint.json
|
||||
docs/
|
||||
**/.cliff-jumperrc.json
|
||||
**/api-extractor.json
|
||||
**/api-extractor-docs.json
|
||||
**/.eslintignore
|
||||
**/.eslintrc.json
|
||||
**/.lintstagedrc.js
|
||||
**/.lintstagedrc.cjs
|
||||
**/.lintstagedrc.json
|
||||
**/.prettierignore
|
||||
**/.prettierrc.js
|
||||
**/.prettierrc.cjs
|
||||
**/.prettierrc.json
|
||||
**/cliff.toml
|
||||
**/CHANGELOG.md
|
||||
**/README.md
|
||||
**/LICENSE
|
||||
**/tsconfig.eslint.json
|
||||
**/tsconfig.docs.json
|
||||
**/docs/
|
||||
**/vitest.config.ts
|
||||
|
||||
|
||||
@@ -2,13 +2,10 @@
|
||||
"root": true,
|
||||
"extends": ["neon/common", "neon/node", "neon/typescript", "neon/prettier"],
|
||||
"parserOptions": {
|
||||
"project": "./tsconfig.eslint.json"
|
||||
"project": ["./tsconfig.eslint.json", "./apps/*/tsconfig.eslint.json", "./packages/*/tsconfig.eslint.json"]
|
||||
},
|
||||
"rules": {
|
||||
"@typescript-eslint/consistent-type-definitions": ["error", "interface"]
|
||||
},
|
||||
"ignorePatterns": ["**/dist/*"],
|
||||
"env": {
|
||||
"jest": true
|
||||
}
|
||||
"ignorePatterns": ["**/dist/*"]
|
||||
}
|
||||
|
||||
28
.github/CODEOWNERS
vendored
Normal file
@@ -0,0 +1,28 @@
|
||||
# Learn how to add code owners here:
|
||||
# https://help.github.com/en/articles/about-code-owners
|
||||
|
||||
* @iCrawl
|
||||
|
||||
/apps/guide/ @discordjs/website @discordjs/guide
|
||||
/apps/guide/src/content/ @discordjs/guide
|
||||
/apps/website/ @discordjs/website
|
||||
|
||||
/packages/actions/ @discordjs/actions
|
||||
/packages/api-extractor-utils/ @discordjs/api-extractor-utils
|
||||
/packages/brokers/ @discordjs/brokers
|
||||
/packages/builders/ @discordjs/builders
|
||||
/packages/collection/ @discordjs/collection
|
||||
/packages/core/ @discordjs/core
|
||||
/packages/create-discord-bot/ @discordjs/guide
|
||||
/packages/discord.js/ @discordjs/core
|
||||
/packages/docgen/ @iCrawl
|
||||
/packages/formatters/ @discordjs/formatters
|
||||
/packages/next/ @discordjs/core
|
||||
/packages/proxy/ @discordjs/proxy
|
||||
/packages/proxy-container/ @discordjs/proxy
|
||||
/packages/rest/ @discordjs/rest
|
||||
/packages/scripts/ @discordjs/scripts
|
||||
/packages/ui/ @discordjs/ui
|
||||
/packages/util/ @discordjs/util
|
||||
/packages/voice/ @discordjs/core
|
||||
/packages/ws/ @discordjs/ws
|
||||
2
.github/CONTRIBUTING.md
vendored
@@ -45,4 +45,4 @@ yarn create-package <package-name> [package-description]
|
||||
```
|
||||
|
||||
This will create new package directory under `packages/` with the required configuration files. You can
|
||||
begin to make changes within the `src/` directory.
|
||||
begin to make changes within the `src/` directory. It may also be required to update the CODEOWNERS file.
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
name: Bug report
|
||||
description: Report incorrect or unexpected behavior of a package
|
||||
description: Report an issue with discord.js or another package.
|
||||
labels: [bug, need repro]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
Use Discord for questions: https://discord.gg/djs
|
||||
Thank you for filing an issue! If you are here to ask a question, use Discord instead: https://discord.gg/djs
|
||||
|
||||
This issue form is for discord.js, including other packages.
|
||||
- type: dropdown
|
||||
id: package
|
||||
attributes:
|
||||
@@ -16,11 +18,14 @@ body:
|
||||
- builders
|
||||
- collection
|
||||
- core
|
||||
- create-discord-bot
|
||||
- formatters
|
||||
- next
|
||||
- proxy
|
||||
- proxy-container
|
||||
- rest
|
||||
- ui
|
||||
- util
|
||||
- voice
|
||||
- ws
|
||||
validations:
|
||||
@@ -29,57 +34,44 @@ body:
|
||||
id: description
|
||||
attributes:
|
||||
label: Issue description
|
||||
description: |
|
||||
Describe the issue in as much detail as possible.
|
||||
|
||||
Tip: You can attach images or log files by clicking this area to highlight it and then dragging files into it.
|
||||
description: Describe the issue in as much detail as possible.
|
||||
placeholder: |
|
||||
Steps to reproduce with below code sample:
|
||||
1. do thing
|
||||
2. do thing in Discord client
|
||||
3. observe behavior
|
||||
4. see error logs below
|
||||
1. Do thing
|
||||
2. Do thing in Discord client
|
||||
3. Observe behavior
|
||||
4. See error logs below
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: codesample
|
||||
id: code_sample
|
||||
attributes:
|
||||
label: Code sample
|
||||
description: Include a reproducible, minimal code sample. This will be automatically formatted into code, so no need for backticks.
|
||||
render: typescript
|
||||
placeholder: |
|
||||
Your code sample should be...
|
||||
... Minimal - Use as little code as possible that still produces the same problem (and is understandable)
|
||||
... Complete - Provide all parts someone else needs to reproduce your problem
|
||||
... Reproducible - Test the code you're about to provide to make sure it reproduces the problem
|
||||
- type: input
|
||||
id: djs-version
|
||||
attributes:
|
||||
label: Package version
|
||||
description: Which version of the package are you using? Run `npm list <package>` in your project directory and paste the output.
|
||||
placeholder: We no longer support version 12 or earlier of discord.js
|
||||
validations:
|
||||
required: true
|
||||
- type: input
|
||||
id: node-version
|
||||
attributes:
|
||||
label: Node.js version
|
||||
description: |
|
||||
Which version of Node.js are you using? Run `node --version` in your project directory and paste the output.
|
||||
If you are using TypeScript, please include its version (`npm list typescript`) as well.
|
||||
placeholder: Node.js version 16.9+ is required for version 14.0.0+
|
||||
Your code sample should be:
|
||||
1. Minimal - Use as little code as possible that still produces the same problem (and is understandable)
|
||||
2. Complete - Provide all parts someone else needs to reproduce your problem
|
||||
3. Reproducible - Test the code you're about to provide to make sure it reproduces the problem
|
||||
|
||||
This will be automatically formatted into code, so no need for backticks.
|
||||
render: typescript
|
||||
- type: textarea
|
||||
id: versions
|
||||
attributes:
|
||||
label: Versions
|
||||
description: List necessary versions here. This includes your package version, runtime version, operating system etc.
|
||||
placeholder: |
|
||||
- discord.js 14.9.0 (`npm ls discord.js` or another package)
|
||||
- Node.js 16.9.0 (`node --version`)
|
||||
- TypeScript 5.0.4 (`npm ls typescript` if you use it)
|
||||
- macOS Ventura 13.3.1
|
||||
validations:
|
||||
required: true
|
||||
- type: input
|
||||
id: os
|
||||
attributes:
|
||||
label: Operating system
|
||||
description: Which OS does your application run on?
|
||||
- type: dropdown
|
||||
id: priority
|
||||
attributes:
|
||||
label: Priority this issue should have
|
||||
description: Please be realistic. If you need to elaborate on your reasoning, please use the Issue description field above.
|
||||
label: Issue priority
|
||||
description: Please be realistic. If you need to elaborate on your reasoning, please use the issue description field above.
|
||||
options:
|
||||
- Low (slightly annoying)
|
||||
- Medium (should be fixed soon)
|
||||
@@ -90,12 +82,9 @@ body:
|
||||
id: partials
|
||||
attributes:
|
||||
label: Which partials do you have configured?
|
||||
description: |
|
||||
Check your Client constructor for the `partials` key.
|
||||
|
||||
Tip: you can select multiple items
|
||||
description: Check your `Client` constructor for the `partials` key.
|
||||
options:
|
||||
- Not applicable (subpackage bug)
|
||||
- Not applicable
|
||||
- No Partials
|
||||
- User
|
||||
- Channel
|
||||
@@ -111,12 +100,9 @@ body:
|
||||
id: intents
|
||||
attributes:
|
||||
label: Which gateway intents are you subscribing to?
|
||||
description: |
|
||||
Check your Client constructor options for the `intents` key.
|
||||
|
||||
Tip: you can select multiple items
|
||||
description: Check your `Client` constructor for the `intents` key.
|
||||
options:
|
||||
- Not applicable (subpackage bug)
|
||||
- Not applicable
|
||||
- No Intents
|
||||
- Guilds
|
||||
- GuildMembers
|
||||
@@ -141,7 +127,7 @@ body:
|
||||
validations:
|
||||
required: true
|
||||
- type: input
|
||||
id: dev-release
|
||||
id: dev_release
|
||||
attributes:
|
||||
label: I have tested this issue on a development release
|
||||
placeholder: d23280c (commit hash)
|
||||
58
.github/ISSUE_TEMPLATE/02-application_bug_report.yml
vendored
Normal file
@@ -0,0 +1,58 @@
|
||||
name: Websites bug report
|
||||
description: Report an issue with the documentation or guide websites.
|
||||
labels: [bug, need repro]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
Thank you for filing an issue! If you are here to ask a question, use Discord instead: https://discord.gg/djs
|
||||
|
||||
This issue form is for our documentation and guide websites.
|
||||
- type: dropdown
|
||||
id: application
|
||||
attributes:
|
||||
label: Which application is this bug report for?
|
||||
options:
|
||||
- Documentation
|
||||
- Guide
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: description
|
||||
attributes:
|
||||
label: Issue description
|
||||
description: Describe the issue in as much detail as possible.
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: steps_to_reproduce
|
||||
attributes:
|
||||
label: Steps to Reproduce
|
||||
description: What steps must be taken to reproduce this issue?
|
||||
placeholder: |
|
||||
1. Visit a page
|
||||
2. Click a link
|
||||
3. ...
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: versions
|
||||
attributes:
|
||||
label: Versions
|
||||
description: List necessary versions here. This includes your browser, operating system etc.
|
||||
placeholder: |
|
||||
- Safari 16.4 (18615.1.26.11.23)
|
||||
- macOS Ventura 13.3.1
|
||||
validations:
|
||||
required: true
|
||||
- type: dropdown
|
||||
id: priority
|
||||
attributes:
|
||||
label: Issue priority
|
||||
description: Please be realistic. If you need to elaborate on your reasoning, please use the issue description field above.
|
||||
options:
|
||||
- Low (slightly annoying)
|
||||
- Medium (should be fixed soon)
|
||||
- High (immediate attention needed)
|
||||
validations:
|
||||
required: true
|
||||
@@ -9,20 +9,25 @@ body:
|
||||
We do not implement unreleased features.
|
||||
Use Discord for questions: https://discord.gg/djs
|
||||
- type: dropdown
|
||||
id: package
|
||||
id: application_or_package
|
||||
attributes:
|
||||
label: Which package is this feature request for?
|
||||
label: Which application or package is this feature request for?
|
||||
options:
|
||||
- discord.js
|
||||
- Documentation
|
||||
- Guide
|
||||
- brokers
|
||||
- builders
|
||||
- collection
|
||||
- core
|
||||
- create-discord-bot
|
||||
- formatters
|
||||
- next
|
||||
- proxy
|
||||
- proxy-container
|
||||
- rest
|
||||
- ui
|
||||
- util
|
||||
- voice
|
||||
- ws
|
||||
validations:
|
||||
@@ -48,7 +53,7 @@ body:
|
||||
label: Alternative solutions or implementations
|
||||
description: A clear and concise description of any alternative solutions or features you have considered.
|
||||
- type: textarea
|
||||
id: additional-context
|
||||
id: additional_context
|
||||
attributes:
|
||||
label: Other context
|
||||
description: Any other context, screenshots, or file uploads that help us understand your feature request.
|
||||
8
.github/auto_assign.yml
vendored
@@ -1,8 +0,0 @@
|
||||
addReviewers: true
|
||||
reviewers:
|
||||
- iCrawl
|
||||
- SpaceEEC
|
||||
- kyranet
|
||||
- vladfrangu
|
||||
numberOfReviewers: 0
|
||||
runOnDraft: true
|
||||
51
.github/issue-labeler.yml
vendored
@@ -1,24 +1,51 @@
|
||||
apps:guide:
|
||||
- "### Which (application|package|application or package) is this (bug
|
||||
report|feature request) for\\?\\n\\nGuide\\n"
|
||||
apps:website:
|
||||
- "### Which (application|package|application or package) is this (bug
|
||||
report|feature request) for\\?\\n\\nDocumentation\\n"
|
||||
packages:brokers:
|
||||
- '### Which package is this (bug report|feature request) for\?\n\nbrokers'
|
||||
- "### Which (application|package|application or package) is this (bug
|
||||
report|feature request) for\\?\\n\\nbrokers\\n"
|
||||
packages:builders:
|
||||
- '### Which package is this (bug report|feature request) for\?\n\nbuilders'
|
||||
- "### Which (application|package|application or package) is this (bug
|
||||
report|feature request) for\\?\\n\\nbuilders\\n"
|
||||
packages:collection:
|
||||
- '### Which package is this (bug report|feature request) for\?\n\ncollection'
|
||||
- "### Which (application|package|application or package) is this (bug
|
||||
report|feature request) for\\?\\n\\ncollection\\n"
|
||||
packages:core:
|
||||
- '### Which package is this (bug report|feature request) for\?\n\ncore'
|
||||
- "### Which (application|package|application or package) is this (bug
|
||||
report|feature request) for\\?\\n\\ncore\\n"
|
||||
packages:create-discord-bot:
|
||||
- "### Which (application|package|application or package) is this (bug
|
||||
report|feature request) for\\?\\n\\ncreate-discord-bot\\n"
|
||||
packages:discord.js:
|
||||
- '### Which package is this (bug report|feature request) for\?\n\ndiscord.js'
|
||||
- "### Which (application|package|application or package) is this (bug
|
||||
report|feature request) for\\?\\n\\ndiscord.js\\n"
|
||||
packages:formatters:
|
||||
- '### Which package is this (bug report|feature request) for\?\n\nformatters'
|
||||
- "### Which (application|package|application or package) is this (bug
|
||||
report|feature request) for\\?\\n\\nformatters\\n"
|
||||
packages:next:
|
||||
- '### Which package is this (bug report|feature request) for\?\n\nnext'
|
||||
- "### Which (application|package|application or package) is this (bug
|
||||
report|feature request) for\\?\\n\\nnext\\n"
|
||||
packages:proxy:
|
||||
- '### Which package is this (bug report|feature request) for\?\n\nproxy'
|
||||
- "### Which (application|package|application or package) is this (bug
|
||||
report|feature request) for\\?\\n\\nproxy\\n"
|
||||
packages:proxy-container:
|
||||
- '### Which package is this (bug report|feature request) for\?\n\nproxy-container'
|
||||
- "### Which (application|package|application or package) is this (bug
|
||||
report|feature request) for\\?\\n\\nproxy-container\\n"
|
||||
packages:rest:
|
||||
- '### Which package is this (bug report|feature request) for\?\n\nrest'
|
||||
- "### Which (application|package|application or package) is this (bug
|
||||
report|feature request) for\\?\\n\\nrest\\n"
|
||||
packages:ui:
|
||||
- "### Which (application|package|application or package) is this (bug
|
||||
report|feature request) for\\?\\n\\ui\\n"
|
||||
packages:util:
|
||||
- "### Which (application|package|application or package) is this (bug
|
||||
report|feature request) for\\?\\n\\util\\n"
|
||||
packages:voice:
|
||||
- '### Which package is this (bug report|feature request) for\?\n\nvoice'
|
||||
- "### Which (application|package|application or package) is this (bug
|
||||
report|feature request) for\\?\\n\\nvoice\\n"
|
||||
packages:ws:
|
||||
- '### Which package is this (bug report|feature request) for\?\n\nws'
|
||||
- "### Which (application|package|application or package) is this (bug
|
||||
report|feature request) for\\?\\n\\nws\\n"
|
||||
|
||||
9
.github/labeler.yml
vendored
@@ -16,18 +16,21 @@ packages:collection:
|
||||
packages:core:
|
||||
- packages/core/*
|
||||
- packages/core/**/*
|
||||
packages:create-discord-bot:
|
||||
- packages/create-discord-bot/*
|
||||
- packages/create-discord-bot/**/*
|
||||
packages:discord.js:
|
||||
- packages/discord.js/*
|
||||
- packages/discord.js/**/*
|
||||
packages:next:
|
||||
- packages/next/*
|
||||
- packages/next/**/*
|
||||
packages:docgen:
|
||||
- packages/docgen/*
|
||||
- packages/docgen/**/*
|
||||
packages:formatters:
|
||||
- packages/formatters/*
|
||||
- packages/formatters/**/*
|
||||
packages:next:
|
||||
- packages/next/*
|
||||
- packages/next/**/*
|
||||
packages:proxy:
|
||||
- packages/proxy/*
|
||||
- packages/proxy/**/*
|
||||
|
||||
14
.github/labels.yml
vendored
@@ -1,7 +1,7 @@
|
||||
- name: api changes
|
||||
color: '5663e9'
|
||||
color: 5663e9
|
||||
- name: api support
|
||||
color: '5663e9'
|
||||
color: 5663e9
|
||||
- name: apps:guide
|
||||
color: fbca04
|
||||
- name: apps:website
|
||||
@@ -23,7 +23,7 @@
|
||||
- name: dependencies
|
||||
color: 276bd1
|
||||
- name: discord
|
||||
color: '5663e9'
|
||||
color: 5663e9
|
||||
- name: discussion
|
||||
color: b6b1f9
|
||||
- name: documentation
|
||||
@@ -41,7 +41,7 @@
|
||||
- name: has PR
|
||||
color: 4b1f8e
|
||||
- name: help wanted
|
||||
color: '008672'
|
||||
color: 008672
|
||||
- name: in progress
|
||||
color: ffccd7
|
||||
- name: in review
|
||||
@@ -60,14 +60,16 @@
|
||||
color: fbca04
|
||||
- name: packages:core
|
||||
color: fbca04
|
||||
- name: packages:discord.js
|
||||
- name: packages:create-discord-bot
|
||||
color: fbca04
|
||||
- name: packages:next
|
||||
- name: packages:discord.js
|
||||
color: fbca04
|
||||
- name: packages:docgen
|
||||
color: fbca04
|
||||
- name: packages:formatters
|
||||
color: fbca04
|
||||
- name: packages:next
|
||||
color: fbca04
|
||||
- name: packages:proxy
|
||||
color: fbca04
|
||||
- name: packages:proxy-container
|
||||
|
||||
BIN
.github/powered-by-workers.png
vendored
Normal file
|
After Width: | Height: | Size: 16 KiB |
119
.github/workflows/documentation.yml
vendored
@@ -24,7 +24,7 @@ concurrency:
|
||||
cancel-in-progress: true
|
||||
jobs:
|
||||
build:
|
||||
name: Build documentation
|
||||
name: Build & upload documentation
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
|
||||
@@ -36,10 +36,10 @@ jobs:
|
||||
with:
|
||||
ref: ${{ inputs.ref || '' }}
|
||||
|
||||
- name: Install node.js v16
|
||||
- name: Install node.js v18
|
||||
uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: 16
|
||||
node-version: 18
|
||||
|
||||
- name: Install dependencies
|
||||
uses: ./packages/actions/src/yarnCache
|
||||
@@ -50,71 +50,6 @@ jobs:
|
||||
- name: Build docs
|
||||
run: yarn docs
|
||||
|
||||
- name: Upload docgen artifacts
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: docgen
|
||||
path: packages/*/docs/docs.json
|
||||
|
||||
- name: Upload api-extractor artifacts
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: api-extractor
|
||||
path: packages/*/docs/docs.api.json
|
||||
|
||||
upload:
|
||||
name: Upload Documentation
|
||||
needs: build
|
||||
strategy:
|
||||
max-parallel: 1
|
||||
fail-fast: false
|
||||
matrix:
|
||||
package:
|
||||
[
|
||||
'brokers',
|
||||
'builders',
|
||||
'collection',
|
||||
'core',
|
||||
'discord.js',
|
||||
'next',
|
||||
'formatters',
|
||||
'proxy',
|
||||
'rest',
|
||||
'util',
|
||||
'voice',
|
||||
'ws',
|
||||
]
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
|
||||
TURBO_TEAM: ${{ secrets.TURBO_TEAM }}
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Install node.js v16
|
||||
uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: 16
|
||||
|
||||
- name: Install dependencies
|
||||
uses: ./packages/actions/src/yarnCache
|
||||
|
||||
- name: Build actions
|
||||
run: yarn workspace @discordjs/actions build
|
||||
|
||||
- name: Download docgen artifacts
|
||||
uses: actions/download-artifact@v3
|
||||
with:
|
||||
name: docgen
|
||||
path: docs
|
||||
|
||||
- name: Download api-extractor artifacts
|
||||
uses: actions/download-artifact@v3
|
||||
with:
|
||||
name: api-extractor
|
||||
path: docs
|
||||
|
||||
- name: Checkout docs repository
|
||||
uses: actions/checkout@v3
|
||||
with:
|
||||
@@ -129,22 +64,8 @@ jobs:
|
||||
with:
|
||||
tag: ${{ github.ref_name }}
|
||||
|
||||
- name: Move docs to correct directory
|
||||
if: ${{ github.ref_type == 'tag' && matrix.package == steps.extract-tag.outputs.package }}
|
||||
env:
|
||||
PACKAGE: ${{ steps.extract-tag.outputs.package }}
|
||||
SEMVER: ${{ steps.extract-tag.outputs.semver }}
|
||||
run: |
|
||||
mkdir -p out/${PACKAGE}
|
||||
if [[ $PACKAGE == "discord.js" ]]; then
|
||||
mv docs/${PACKAGE}/docs/docs.json out/${PACKAGE}/${SEMVER}.json
|
||||
fi
|
||||
if [[ $PACKAGE != "discord.js" ]]; then
|
||||
mv docs/${PACKAGE}/docs/docs.api.json out/${PACKAGE}/${SEMVER}.api.json
|
||||
fi
|
||||
|
||||
- name: Upload documentation to database
|
||||
if: ${{ github.ref_type == 'tag' && matrix.package == steps.extract-tag.outputs.package }}
|
||||
if: ${{ github.ref_type == 'tag' }}
|
||||
env:
|
||||
DATABASE_URL: ${{ secrets.DATABASE_URL }}
|
||||
uses: ./packages/actions/src/uploadDocumentation
|
||||
@@ -153,16 +74,16 @@ jobs:
|
||||
version: ${{ steps.extract-tag.outputs.semver }}
|
||||
|
||||
- name: Move docs to correct directory
|
||||
if: ${{ github.ref_type == 'branch' }}
|
||||
if: ${{ github.ref_type == 'tag' }}
|
||||
env:
|
||||
PACKAGE: ${{ matrix.package }}
|
||||
PACKAGE: ${{ steps.extract-tag.outputs.package }}
|
||||
SEMVER: ${{ steps.extract-tag.outputs.semver }}
|
||||
run: |
|
||||
mkdir -p out/${PACKAGE}
|
||||
if [[ $PACKAGE == "discord.js" ]]; then
|
||||
mv docs/${PACKAGE}/docs/docs.json out/${PACKAGE}/${GITHUB_REF_NAME}.json
|
||||
fi
|
||||
if [[ $PACKAGE != "discord.js" ]]; then
|
||||
mv docs/${PACKAGE}/docs/docs.api.json out/${PACKAGE}/${GITHUB_REF_NAME}.api.json
|
||||
mkdir -p "out/${PACKAGE}"
|
||||
if [[ "${PACKAGE}" == "discord.js" ]]; then
|
||||
mv "packages/${PACKAGE}/docs/docs.json" "out/${PACKAGE}/${SEMVER}.json"
|
||||
else
|
||||
mv "packages/${PACKAGE}/docs/docs.api.json" "out/${PACKAGE}/${SEMVER}.api.json"
|
||||
fi
|
||||
|
||||
- name: Upload documentation to database
|
||||
@@ -170,8 +91,20 @@ jobs:
|
||||
env:
|
||||
DATABASE_URL: ${{ secrets.DATABASE_URL }}
|
||||
uses: ./packages/actions/src/uploadDocumentation
|
||||
with:
|
||||
package: ${{ matrix.package }}
|
||||
|
||||
- name: Move docs to correct directory
|
||||
if: ${{ github.ref_type == 'branch' }}
|
||||
run: |
|
||||
declare -a PACKAGES=("brokers" "builders" "collection" "core" "discord.js" "next" "formatters" "proxy" "rest" "util" "voice" "ws")
|
||||
for PACKAGE in "${PACKAGES[@]}"; do
|
||||
if [[ "${PACKAGE}" == "discord.js" ]]; then
|
||||
mkdir -p "out/${PACKAGE}"
|
||||
mv "packages/${PACKAGE}/docs/docs.json" "out/${PACKAGE}/${GITHUB_REF_NAME}.json"
|
||||
else
|
||||
mkdir -p "out/${PACKAGE}"
|
||||
mv "packages/${PACKAGE}/docs/docs.api.json" "out/${PACKAGE}/${GITHUB_REF_NAME}.api.json"
|
||||
fi
|
||||
done
|
||||
|
||||
- name: Commit and push
|
||||
run: |
|
||||
|
||||
2
.github/workflows/issue-triage.yml
vendored
@@ -6,7 +6,7 @@ jobs:
|
||||
issue-triage:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: github/issue-labeler@v2.5
|
||||
- uses: github/issue-labeler@v3.1
|
||||
with:
|
||||
repo-token: '${{ secrets.GITHUB_TOKEN }}'
|
||||
configuration-path: .github/issue-labeler.yml
|
||||
|
||||
4
.github/workflows/lighthouse.yml
vendored
@@ -10,7 +10,7 @@ jobs:
|
||||
steps:
|
||||
- name: Get Vercel preview URL
|
||||
id: get_preview_url
|
||||
uses: actions/github-script@v3
|
||||
uses: actions/github-script@v6
|
||||
with:
|
||||
script: |
|
||||
const comment = context.payload.comment;
|
||||
@@ -53,7 +53,7 @@ jobs:
|
||||
- name: Format lighthouse score
|
||||
if: ${{ steps.get_preview_url.outputs.vercel_preview_url != '' }}
|
||||
id: format_lighthouse_score
|
||||
uses: actions/github-script@v3
|
||||
uses: actions/github-script@v6
|
||||
with:
|
||||
script: |
|
||||
const result = ${{ steps.lighthouse_audit.outputs.manifest }}[0].summary
|
||||
|
||||
102
.github/workflows/nextjs-bundle-analysis.yml
vendored
@@ -1,102 +0,0 @@
|
||||
name: 'Next.js Bundle Analysis'
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- 'main'
|
||||
pull_request_target:
|
||||
paths:
|
||||
- 'apps/website/**'
|
||||
workflow_dispatch:
|
||||
defaults:
|
||||
run:
|
||||
working-directory: apps/website
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
pull-requests: write
|
||||
jobs:
|
||||
analyze:
|
||||
name: Analyze
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Install node.js v16
|
||||
uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: 16
|
||||
|
||||
- name: Install dependencies
|
||||
uses: ./packages/actions/src/yarnCache
|
||||
|
||||
- name: Restore next build
|
||||
uses: actions/cache@v3
|
||||
id: restore-build-cache
|
||||
env:
|
||||
cache-name: cache-next-build
|
||||
with:
|
||||
path: apps/website/.next/cache
|
||||
key: ${{ runner.os }}-build-${{ env.cache-name }}
|
||||
|
||||
- name: Build packages
|
||||
run: yarn run --top-level build
|
||||
|
||||
- name: Build website
|
||||
run: yarn workspace @discordjs/website run build:local
|
||||
|
||||
- name: Analyze bundle
|
||||
run: npx -yes -p github:hashicorp/nextjs-bundle-analysis report
|
||||
|
||||
- name: Upload bundle
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: bundle
|
||||
path: apps/website/.next/analyze/__bundle_analysis.json
|
||||
|
||||
- name: Download base branch bundle stats
|
||||
uses: dawidd6/action-download-artifact@v2
|
||||
if: success() && github.event.number
|
||||
with:
|
||||
workflow: nextjs-bundle-analysis.yml
|
||||
commit: ${{ github.event.pull_request.base.sha }}
|
||||
path: apps/website/.next/analyze/base
|
||||
|
||||
- name: Compare with base branch bundle
|
||||
if: success() && github.event.number
|
||||
run: ls -laR .next/analyze/base && npx -yes -p github:hashicorp/nextjs-bundle-analysis compare
|
||||
|
||||
- name: Get comment body
|
||||
id: get-comment-body
|
||||
if: success() && github.event.number
|
||||
uses: actions/github-script@v6
|
||||
with:
|
||||
result-encoding: string
|
||||
script: |
|
||||
const fs = require('fs');
|
||||
const comment = fs.readFileSync('apps/website/.next/analyze/__bundle_analysis_comment.txt', 'utf8');
|
||||
core.setOutput('body', comment);
|
||||
|
||||
- name: Find Comment
|
||||
uses: peter-evans/find-comment@v2
|
||||
if: success() && github.event.number
|
||||
id: fc
|
||||
with:
|
||||
issue-number: ${{ github.event.number }}
|
||||
body-includes: '<!-- __NEXTJS_BUNDLE -->'
|
||||
|
||||
- name: Create Comment
|
||||
uses: peter-evans/create-or-update-comment@v2
|
||||
if: success() && github.event.number && steps.fc.outputs.comment-id == 0
|
||||
with:
|
||||
issue-number: ${{ github.event.number }}
|
||||
body: ${{ steps.get-comment-body.outputs.body }}
|
||||
|
||||
- name: Update Comment
|
||||
uses: peter-evans/create-or-update-comment@v2
|
||||
if: success() && github.event.number && steps.fc.outputs.comment-id != 0
|
||||
with:
|
||||
issue-number: ${{ github.event.number }}
|
||||
body: ${{ steps.get-comment-body.outputs.body }}
|
||||
comment-id: ${{ steps.fc.outputs.comment-id }}
|
||||
edit-mode: replace
|
||||
4
.github/workflows/npm-auto-deprecate.yml
vendored
@@ -12,10 +12,10 @@ jobs:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Install node.js v16
|
||||
- name: Install node.js v18
|
||||
uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: 16
|
||||
node-version: 18
|
||||
|
||||
- name: Install dependencies
|
||||
uses: ./packages/actions/src/yarnCache
|
||||
|
||||
4
.github/workflows/pr-triage.yml
vendored
@@ -11,7 +11,3 @@ jobs:
|
||||
with:
|
||||
repo-token: '${{ secrets.GITHUB_TOKEN }}'
|
||||
sync-labels: true
|
||||
|
||||
- name: Automatically assign reviewers
|
||||
if: github.event.action == 'opened'
|
||||
uses: kentaro-m/auto-assign-action@v1.2.3
|
||||
|
||||
11
.github/workflows/publish-dev-docker.yml
vendored
@@ -12,10 +12,10 @@ jobs:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Install node.js v16
|
||||
- name: Install node.js v18
|
||||
uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: 16
|
||||
node-version: 18
|
||||
|
||||
- name: Install dependencies
|
||||
uses: ./packages/actions/src/yarnCache
|
||||
@@ -29,8 +29,5 @@ jobs:
|
||||
- name: Login to DockerHub
|
||||
run: echo ${{ secrets.DOCKER_ACCESS_TOKEN }} | docker login -u ${{ secrets.DOCKER_USERNAME }} --password-stdin
|
||||
|
||||
- name: Build the image
|
||||
run: yarn docker build @discordjs/proxy-container -t discordjs/proxy:latest
|
||||
|
||||
- name: Push image to DockerHub
|
||||
run: docker push discordjs/proxy:latest
|
||||
- name: Build & push docker image
|
||||
run: yarn docker build --buildkit @discordjs/proxy-container -t discordjs/proxy:latest --push
|
||||
|
||||
6
.github/workflows/publish-dev.yml
vendored
@@ -42,11 +42,13 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Install node.js v16
|
||||
- name: Install node.js v18
|
||||
uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: 16
|
||||
node-version: 18
|
||||
registry-url: https://registry.npmjs.org/
|
||||
|
||||
- name: Install dependencies
|
||||
|
||||
14
.github/workflows/publish-docker.yml
vendored
@@ -9,10 +9,10 @@ jobs:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Install node.js v16
|
||||
- name: Install node.js v18
|
||||
uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: 16
|
||||
node-version: 18
|
||||
|
||||
- name: Install dependencies
|
||||
uses: ./packages/actions/src/yarnCache
|
||||
@@ -26,11 +26,5 @@ jobs:
|
||||
- name: Login to DockerHub
|
||||
run: echo ${{ secrets.DOCKER_ACCESS_TOKEN }} | docker login -u ${{ secrets.DOCKER_USERNAME }} --password-stdin
|
||||
|
||||
- name: Build docker image
|
||||
run: yarn docker build @discordjs/proxy-container -t discordjs/proxy:latest
|
||||
|
||||
- name: Tag image with major
|
||||
run: docker tag discordjs/proxy discordjs/proxy:$(cut -d '.' -f1 <<< $(jq --raw-output '.version' packages/proxy-container/package.json))
|
||||
|
||||
- name: Push image to DockerHub
|
||||
run: docker push --all-tags discordjs/proxy
|
||||
- name: Build & push docker image
|
||||
run: yarn docker build --buildkit @discordjs/proxy-container -t discordjs/proxy:$(cut -d '.' -f1 <<< $(jq --raw-output '.version' packages/proxy-container/package.json)) --push
|
||||
|
||||
4
.github/workflows/publish-release.yml
vendored
@@ -14,10 +14,10 @@ jobs:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Install node.js v16
|
||||
- name: Install node.js v18
|
||||
uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: 16
|
||||
node-version: 18
|
||||
registry-url: https://registry.npmjs.org/
|
||||
|
||||
- name: Install dependencies
|
||||
|
||||
4
.github/workflows/tests.yml
vendored
@@ -19,10 +19,10 @@ jobs:
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Install node.js v16
|
||||
- name: Install node.js v18
|
||||
uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: 16
|
||||
node-version: 18
|
||||
|
||||
- name: Install dependencies
|
||||
uses: ./packages/actions/src/yarnCache
|
||||
|
||||
18
.gitignore
vendored
@@ -1,8 +1,8 @@
|
||||
# Packages
|
||||
node_modules/
|
||||
node_modules
|
||||
|
||||
# Log files
|
||||
logs/
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
|
||||
@@ -15,20 +15,20 @@ pids
|
||||
.env
|
||||
|
||||
# Dist
|
||||
dist/
|
||||
dist-docs/
|
||||
dist
|
||||
dist-docs
|
||||
|
||||
# Miscellaneous
|
||||
.tmp/
|
||||
.vscode/*
|
||||
.tmp
|
||||
.vscode
|
||||
!.vscode/extensions.json
|
||||
!.vscode/settings.json
|
||||
.idea/
|
||||
.idea
|
||||
.DS_Store
|
||||
.turbo
|
||||
tsconfig.tsbuildinfo
|
||||
coverage/
|
||||
out/
|
||||
coverage
|
||||
out
|
||||
|
||||
# yarn
|
||||
.pnp.*
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"*": "prettier --ignore-unknown --write",
|
||||
"{src/**,__tests__/**}.{mjs,js,cjs,ts,tsx,astro}": "eslint --ext .mjs,.js,.cjs,.ts,.tsx,.astro --fix",
|
||||
"{src/**,__tests__/**}.{mjs,js,cjs,ts,tsx}": "eslint --ext .mjs,.js,.cjs,.ts,.tsx --fix",
|
||||
"src/**.ts": "vitest related --run --config ../../vitest.config.ts"
|
||||
}
|
||||
|
||||
1
.prettierignore
Normal file
@@ -0,0 +1 @@
|
||||
CODEOWNERS
|
||||
1
.vscode/extensions.json
vendored
@@ -9,7 +9,6 @@
|
||||
"christian-kohler.npm-intellisense",
|
||||
"christian-kohler.path-intellisense",
|
||||
"antfu.unocss",
|
||||
"astro-build.astro-vscode",
|
||||
"unifiedjs.vscode-mdx"
|
||||
]
|
||||
}
|
||||
|
||||
3
.vscode/settings.json
vendored
@@ -1,7 +1,6 @@
|
||||
{
|
||||
"eslint.workingDirectories": [{ "pattern": "./apps/*" }, { "pattern": "./packages/*" }],
|
||||
"eslint.validate": ["javascript", "javascriptreact", "astro", "typescript", "typescriptreact"],
|
||||
"prettier.documentSelectors": ["**/*.astro"],
|
||||
"eslint.validate": ["javascript", "javascriptreact", "typescript", "typescriptreact"],
|
||||
"editor.defaultFormatter": "esbenp.prettier-vscode",
|
||||
"editor.formatOnSave": true,
|
||||
"editor.codeActionsOnSave": {
|
||||
|
||||
18
.yarn/patches/yaml-npm-2.2.2-6e3cddb343.patch
Normal file
@@ -0,0 +1,18 @@
|
||||
diff --git a/package.json b/package.json
|
||||
index fc35658a40f9ba3e3513c459ba9f4f6e1b3f59f5..bc35eda66f270c95ba52e721cb6976fd61622c58 100644
|
||||
--- a/package.json
|
||||
+++ b/package.json
|
||||
@@ -26,11 +26,13 @@
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
+ "types": "./dist/index.d.ts",
|
||||
"node": "./dist/index.js",
|
||||
"default": "./browser/index.js"
|
||||
},
|
||||
"./package.json": "./package.json",
|
||||
"./util": {
|
||||
+ "types": "./dist/util.d.ts",
|
||||
"node": "./dist/util.js",
|
||||
"default": "./browser/dist/util.js"
|
||||
}
|
||||
@@ -215,7 +215,8 @@ module.exports = {
|
||||
await c({ workspace: e, report: t, destination: u });
|
||||
});
|
||||
}
|
||||
await i.execUtils.pipevp('docker', ['build', ...this.args, '-f', s, '.'], {
|
||||
const h = this.buildKit ? ['buildx', 'build'] : ['build'];
|
||||
await i.execUtils.pipevp('docker', [...h, ...this.args, '-f', s, '.'], {
|
||||
cwd: o,
|
||||
strict: !0,
|
||||
stdin: this.context.stdin,
|
||||
@@ -241,6 +242,7 @@ module.exports = {
|
||||
'yarn docker build --copy secret.key --copy config.json @foo/bar',
|
||||
],
|
||||
['Install production dependencies only', 'yarn docker build --production @foo/bar'],
|
||||
['Build a Docker image using BuildKit', 'yarn docker build --buildkit @foo/bar'],
|
||||
],
|
||||
})),
|
||||
d([r.Command.String()], f.prototype, 'workspaceName', void 0),
|
||||
@@ -248,6 +250,7 @@ module.exports = {
|
||||
d([r.Command.String('-f,--file')], f.prototype, 'dockerFilePath', void 0),
|
||||
d([r.Command.Array('--copy')], f.prototype, 'copyFiles', void 0),
|
||||
d([r.Command.Boolean('--production')], f.prototype, 'production', void 0),
|
||||
d([r.Command.Boolean('--buildkit')], f.prototype, 'buildKit', void 0),
|
||||
d([r.Command.Path('docker', 'build')], f.prototype, 'execute', null);
|
||||
const u = { commands: [f] };
|
||||
plugin = e;
|
||||
|
||||
16
.yarnrc.yml
@@ -1,3 +1,17 @@
|
||||
logFilters:
|
||||
# MISSING_PEER_DEPENDENCY
|
||||
- code: YN0002
|
||||
level: discard
|
||||
# FETCH_NOT_CACHED
|
||||
- code: YN0013
|
||||
level: discard
|
||||
# NODE_GYP_INJECTED
|
||||
- code: YN0032
|
||||
level: discard
|
||||
# INCOMPATIBLE_PEER_DEPENDENCY
|
||||
- code: YN0060
|
||||
level: discard
|
||||
|
||||
nodeLinker: node-modules
|
||||
|
||||
plugins:
|
||||
@@ -10,4 +24,4 @@ plugins:
|
||||
- path: .yarn/plugins/@yarnpkg/plugin-docker-build.cjs
|
||||
spec: 'https://github.com/Dcard/yarn-plugins/releases/latest/download/plugin-docker-build.js'
|
||||
|
||||
yarnPath: .yarn/releases/yarn-3.5.0.cjs
|
||||
yarnPath: .yarn/releases/yarn-3.5.1.cjs
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
</p>
|
||||
<p>
|
||||
<a href="https://vercel.com/?utm_source=discordjs&utm_campaign=oss"><img src="https://raw.githubusercontent.com/discordjs/discord.js/main/.github/powered-by-vercel.svg" alt="Vercel" /></a>
|
||||
<a href="https://www.cloudflare.com"><img src="https://raw.githubusercontent.com/discordjs/discord.js/main/.github/powered-by-workers.png" alt="Cloudflare Workers" height="44" /></a>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -88,9 +88,44 @@
|
||||
*
|
||||
* DEFAULT VALUE: no overrideTsconfig section
|
||||
*/
|
||||
// "overrideTsconfig": {
|
||||
// . . .
|
||||
// }
|
||||
"overrideTsconfig": {
|
||||
// Type Checking
|
||||
"allowUnreachableCode": false,
|
||||
"allowUnusedLabels": false,
|
||||
"exactOptionalPropertyTypes": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noImplicitOverride": true,
|
||||
"noImplicitReturns": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"strict": true,
|
||||
"useUnknownInCatchVariables": true,
|
||||
"noUncheckedIndexedAccess": true,
|
||||
|
||||
// Modules
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "node",
|
||||
"resolveJsonModule": true,
|
||||
|
||||
// Emit
|
||||
"declaration": true,
|
||||
"declarationMap": true,
|
||||
"importHelpers": true,
|
||||
"inlineSources": true,
|
||||
"newLine": "lf",
|
||||
"noEmitHelpers": true,
|
||||
"outDir": "dist",
|
||||
"removeComments": false,
|
||||
"sourceMap": true,
|
||||
"esModuleInterop": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
|
||||
// Language and Environment
|
||||
"experimentalDecorators": true,
|
||||
"lib": ["ESNext"],
|
||||
"target": "ES2021",
|
||||
"useDefineForClassFields": true
|
||||
}
|
||||
/**
|
||||
* This option causes the compiler to be invoked with the --skipLibCheck option. This option is not recommended
|
||||
* and may cause API Extractor to produce incomplete or incorrect declarations, but it may be required when
|
||||
@@ -181,7 +216,7 @@
|
||||
/**
|
||||
* (REQUIRED) Whether to generate the .d.ts rollup file.
|
||||
*/
|
||||
"enabled": false
|
||||
"enabled": true,
|
||||
|
||||
/**
|
||||
* Specifies the output path for a .d.ts rollup file to be generated without any trimming.
|
||||
@@ -195,7 +230,7 @@
|
||||
* SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>
|
||||
* DEFAULT VALUE: "<projectFolder>/dist/<unscopedPackageName>.d.ts"
|
||||
*/
|
||||
// "untrimmedFilePath": "<projectFolder>/dist/<unscopedPackageName>.d.ts",
|
||||
"untrimmedFilePath": "<projectFolder>/dist-docs/index.d.ts"
|
||||
|
||||
/**
|
||||
* Specifies the output path for a .d.ts rollup file to be generated with trimming for an "alpha" release.
|
||||
|
||||
1
apps/guide/.eslintignore
Normal file
@@ -0,0 +1 @@
|
||||
next-env.d.ts
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"extends": ["../../.eslintrc.json", "neon/react", "neon/next", "neon/edge", "neon/prettier"],
|
||||
"extends": ["../../.eslintrc.json", "neon/react", "neon/next", "neon/edge", "@unocss", "neon/prettier"],
|
||||
"settings": {
|
||||
"react": {
|
||||
"version": "detect"
|
||||
|
||||
21
apps/guide/.gitignore
vendored
@@ -1,8 +1,8 @@
|
||||
# Packages
|
||||
node_modules/
|
||||
node_modules
|
||||
|
||||
# Log files
|
||||
logs/
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
|
||||
@@ -16,18 +16,13 @@ pids
|
||||
.env*.local
|
||||
|
||||
# Dist
|
||||
dist/
|
||||
typings/
|
||||
.cache/
|
||||
build/
|
||||
.contentlayer
|
||||
.next
|
||||
public/searchIndex
|
||||
src/styles/unocss.css
|
||||
.next/
|
||||
|
||||
# Miscellaneous
|
||||
.tmp/
|
||||
coverage/
|
||||
.vercel
|
||||
public/searchIndex
|
||||
.tmp
|
||||
.vscode
|
||||
lighthouse-results/
|
||||
.contentlayer
|
||||
lighthouse-results
|
||||
|
||||
|
||||
@@ -1,15 +1,7 @@
|
||||
# Autogenerated
|
||||
CHANGELOG.md
|
||||
.contentlayer
|
||||
.next
|
||||
.turbo
|
||||
dist/
|
||||
docs/**/*
|
||||
!docs/index.yml
|
||||
!docs/README.md
|
||||
coverage/
|
||||
.cache
|
||||
build/
|
||||
.vscode
|
||||
coverage
|
||||
src/styles/unocss.css
|
||||
api/
|
||||
.next/
|
||||
.vercel/
|
||||
.cache/
|
||||
next-env.d.ts
|
||||
|
||||
@@ -1,7 +1 @@
|
||||
module.exports = {
|
||||
...require('../../.prettierrc.json'),
|
||||
plugins: [
|
||||
'prettier-plugin-tailwindcss', // MUST come last
|
||||
],
|
||||
pluginSearchDirs: false,
|
||||
};
|
||||
module.exports = require('../../.prettierrc.json');
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
</p>
|
||||
<p>
|
||||
<a href="https://vercel.com/?utm_source=discordjs&utm_campaign=oss"><img src="https://raw.githubusercontent.com/discordjs/discord.js/main/.github/powered-by-vercel.svg" alt="Vercel" /></a>
|
||||
<a href="https://www.cloudflare.com"><img src="https://raw.githubusercontent.com/discordjs/discord.js/main/.github/powered-by-workers.png" alt="Cloudflare Workers" height="44" /></a>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import { remarkCodeHike } from '@code-hike/mdx';
|
||||
import { defineDocumentType, makeSource } from 'contentlayer/source-files';
|
||||
// import { type Node, toString } from 'hast-util-to-string';
|
||||
// import { h } from 'hastscript';
|
||||
// import { escape } from 'html-escaper';
|
||||
// import rehypeAutolinkHeadings from 'rehype-autolink-headings';
|
||||
import { type Node, toString } from 'hast-util-to-string';
|
||||
import { h } from 'hastscript';
|
||||
import { escape } from 'html-escaper';
|
||||
import rehypeAutolinkHeadings from 'rehype-autolink-headings';
|
||||
import rehypeSlug from 'rehype-slug';
|
||||
import remarkGfm from 'remark-gfm';
|
||||
import codeHikeThemeDarkPlus from './src/styles/code-hike-theme-dark-plus.json';
|
||||
|
||||
export const Content = defineDocumentType(() => ({
|
||||
name: 'Content',
|
||||
@@ -16,85 +17,78 @@ export const Content = defineDocumentType(() => ({
|
||||
type: 'string',
|
||||
required: true,
|
||||
},
|
||||
summary: {
|
||||
type: 'string',
|
||||
},
|
||||
image: {
|
||||
category: {
|
||||
type: 'string',
|
||||
required: true,
|
||||
},
|
||||
},
|
||||
computedFields: {
|
||||
slug: {
|
||||
type: 'string',
|
||||
resolve: (doc) => doc._raw.flattenedPath,
|
||||
// eslint-disable-next-line unicorn/prefer-string-replace-all
|
||||
resolve: (doc) => doc._raw.flattenedPath.replace(/\d+-/g, ''),
|
||||
},
|
||||
url: {
|
||||
type: 'string',
|
||||
resolve: (post) => `/posts/${post._raw.flattenedPath}`,
|
||||
// eslint-disable-next-line unicorn/prefer-string-replace-all
|
||||
resolve: (doc) => `/guide/${doc._raw.flattenedPath.replace(/\d+-/g, '')}`,
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
// const LinkIcon = h(
|
||||
// 'svg',
|
||||
// {
|
||||
// width: '1rem',
|
||||
// height: '1rem',
|
||||
// viewBox: '0 0 24 24',
|
||||
// fill: 'none',
|
||||
// stroke: 'currentColor',
|
||||
// strokeWidth: '2',
|
||||
// strokeLinecap: 'round',
|
||||
// strokeLinejoin: 'round',
|
||||
// },
|
||||
// h('path', {
|
||||
// // eslint-disable-next-line id-length
|
||||
// d: 'M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71',
|
||||
// }),
|
||||
// h('path', {
|
||||
// // eslint-disable-next-line id-length
|
||||
// d: 'M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71',
|
||||
// }),
|
||||
// );
|
||||
const LinkIcon = h(
|
||||
'svg',
|
||||
{
|
||||
width: '1.25rem',
|
||||
height: '1.25rem',
|
||||
viewBox: '0 0 24 24',
|
||||
fill: 'none',
|
||||
stroke: 'currentColor',
|
||||
strokeWidth: '2',
|
||||
strokeLinecap: 'round',
|
||||
strokeLinejoin: 'round',
|
||||
},
|
||||
h('path', {
|
||||
// eslint-disable-next-line id-length
|
||||
d: 'M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71',
|
||||
}),
|
||||
h('path', {
|
||||
// eslint-disable-next-line id-length
|
||||
d: 'M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71',
|
||||
}),
|
||||
);
|
||||
|
||||
// const createSROnlyLabel = (text: any) => {
|
||||
// const node = h('span.sr-only', `Section titled ${escape(text)}`);
|
||||
// node.properties!['is:raw'] = true;
|
||||
// return node;
|
||||
// };
|
||||
const createSROnlyLabel = (text: any) => {
|
||||
return h('span', { class: 'sr-only' }, `Section titled ${escape(text)}`);
|
||||
};
|
||||
|
||||
export default makeSource({
|
||||
contentDirPath: 'src/content',
|
||||
documentTypes: [Content],
|
||||
mdx: {
|
||||
remarkPlugins: [remarkGfm, [remarkCodeHike, { theme: 'css-variables', lineNumbers: true }]],
|
||||
remarkPlugins: [remarkGfm, [remarkCodeHike, { theme: codeHikeThemeDarkPlus, lineNumbers: true }]],
|
||||
rehypePlugins: [
|
||||
rehypeSlug,
|
||||
// [
|
||||
// rehypeAutolinkHeadings,
|
||||
// {
|
||||
// properties: {
|
||||
// class:
|
||||
// 'relative inline-flex w-6 h-6 place-items-center place-content-center outline-0 text-black dark:text-white ml-2',
|
||||
// },
|
||||
// behavior: 'after',
|
||||
// group: async ({ tagName }: { tagName: string }) =>
|
||||
// h('div', {
|
||||
// class: `[&>*]:inline-block [&>h1]:m-0 [&>h2]:m-0 [&>h3]:m-0 [&>h4]:m-0 level-${tagName}`,
|
||||
// tabIndex: -1,
|
||||
// }),
|
||||
// content: (heading: Node) => [
|
||||
// h(
|
||||
// `span.anchor-icon`,
|
||||
// {
|
||||
// ariaHidden: 'true',
|
||||
// },
|
||||
// LinkIcon,
|
||||
// ),
|
||||
// createSROnlyLabel(toString(heading)),
|
||||
// ],
|
||||
// },
|
||||
// ],
|
||||
[
|
||||
rehypeAutolinkHeadings,
|
||||
{
|
||||
properties: {
|
||||
class:
|
||||
'relative inline-flex place-items-center place-content-center outline-none text-black dark:text-white pr-2 -ml-8 opacity-0 group-hover:opacity-100',
|
||||
},
|
||||
behavior: 'prepend',
|
||||
content: (heading: Node) => [
|
||||
h(
|
||||
`span.anchor-icon`,
|
||||
{
|
||||
ariaHidden: 'true',
|
||||
},
|
||||
LinkIcon,
|
||||
),
|
||||
createSROnlyLabel(toString(heading)),
|
||||
],
|
||||
},
|
||||
],
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// import { fileURLToPath } from 'node:url';
|
||||
/* eslint-disable @typescript-eslint/no-var-requires */
|
||||
/* eslint-disable @typescript-eslint/no-require-imports */
|
||||
// import bundleAnalyzer from '@next/bundle-analyzer';
|
||||
// import { withContentlayer } from 'next-contentlayer';
|
||||
const { fileURLToPath } = require('node:url');
|
||||
const bundleAnalyzer = require('@next/bundle-analyzer');
|
||||
const { withContentlayer } = require('next-contentlayer');
|
||||
|
||||
@@ -9,19 +9,11 @@ const withBundleAnalyzer = bundleAnalyzer({
|
||||
enabled: process.env.ANALYZE === 'true',
|
||||
});
|
||||
|
||||
module.exports = withContentlayer(
|
||||
withBundleAnalyzer({
|
||||
module.exports = withBundleAnalyzer(
|
||||
withContentlayer({
|
||||
reactStrictMode: true,
|
||||
eslint: {
|
||||
ignoreDuringBuilds: true,
|
||||
},
|
||||
// Until Next.js fixes their type issues
|
||||
typescript: {
|
||||
ignoreBuildErrors: true,
|
||||
},
|
||||
experimental: {
|
||||
appDir: true,
|
||||
fallbackNodePolyfills: false,
|
||||
},
|
||||
images: {
|
||||
dangerouslyAllowSVG: true,
|
||||
|
||||
@@ -7,15 +7,15 @@
|
||||
"test": "vitest run",
|
||||
"test:lighthouse": "lighthouse http://localhost:3000 --output-path=./lighthouse-results",
|
||||
"build:local": "yarn build:prod",
|
||||
"build:prod": "yarn workspaces foreach -ptR run build && yarn build:css && yarn build:next",
|
||||
"build:prod": "yarn build:css && yarn build:next",
|
||||
"build:next": "next build",
|
||||
"build:css": "yarn generate:css",
|
||||
"build:analyze": "cross-env-shell ANALYZE=true yarn build:prod",
|
||||
"build:analyze": "cross-env ANALYZE=true yarn build:prod",
|
||||
"preview": "next start",
|
||||
"dev": "concurrently 'yarn dev:css' 'yarn dev:next'",
|
||||
"dev:next": "next dev",
|
||||
"dev:css": "yarn generate:css --watch",
|
||||
"generate:css": "unocss 'src/**/*.tsx' '../../packages/ui/src/lib/components/**/*.tsx' --out-file ./src/styles/unocss.css --config ../../unocss.config.ts",
|
||||
"generate:css": "unocss 'src/**/*.tsx' 'contentlayer.config.ts' '../../packages/ui/src/lib/components/**/*.tsx' --out-file ./src/styles/unocss.css --config ../../unocss.config.ts",
|
||||
"lint": "prettier --check . && cross-env TIMING=1 eslint src --ext .mjs,.js,.cjs,.ts,.tsx --format=pretty",
|
||||
"format": "prettier --write . && cross-env TIMING=1 eslint src --ext .mjs,.js,.cjs,.ts,.tsx --fix --format=pretty",
|
||||
"fmt": "yarn format"
|
||||
@@ -36,65 +36,63 @@
|
||||
],
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/discordjs/discord.js.git"
|
||||
"url": "https://github.com/discordjs/discord.js.git",
|
||||
"directory": "apps/guide"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/discordjs/discord.js/issues"
|
||||
},
|
||||
"homepage": "https://discord.js.org",
|
||||
"dependencies": {
|
||||
"@code-hike/mdx": "^0.7.5-next.0",
|
||||
"@code-hike/mdx": "^0.9.0",
|
||||
"@discordjs/ui": "workspace:^",
|
||||
"@react-icons/all-files": "^4.1.0",
|
||||
"@vercel/analytics": "^0.1.11",
|
||||
"@vercel/edge-config": "^0.1.5",
|
||||
"@vercel/og": "^0.5.0",
|
||||
"ariakit": "^2.0.0-next.43",
|
||||
"@vercel/analytics": "^1.0.1",
|
||||
"@vercel/edge-config": "^0.2.1",
|
||||
"@vercel/og": "^0.5.9",
|
||||
"ariakit": "^2.0.0-next.44",
|
||||
"cmdk": "^0.2.0",
|
||||
"contentlayer": "^0.3.1",
|
||||
"next": "^13.2.4",
|
||||
"next-contentlayer": "^0.3.1",
|
||||
"contentlayer": "0.3.1",
|
||||
"next": "^13.4.12",
|
||||
"next-contentlayer": "0.3.1",
|
||||
"next-themes": "^0.2.1",
|
||||
"react": "^18.2.0",
|
||||
"react-custom-scrollbars-2": "^4.5.0",
|
||||
"react-dom": "^18.2.0",
|
||||
"react-icons": "^4.8.0",
|
||||
"react-use": "^17.4.0",
|
||||
"rehype-autolink-headings": "^6.1.1",
|
||||
"rehype-ignore": "^1.0.4",
|
||||
"rehype-raw": "^6.1.1",
|
||||
"rehype-slug": "^5.1.0",
|
||||
"remark-gfm": "^3.0.1",
|
||||
"sharp": "^0.32.0"
|
||||
"sharp": "^0.32.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@next/bundle-analyzer": "^13.2.4",
|
||||
"@next/bundle-analyzer": "^13.4.12",
|
||||
"@testing-library/react": "^14.0.0",
|
||||
"@testing-library/user-event": "^14.4.3",
|
||||
"@types/node": "18.15.11",
|
||||
"@types/react": "^18.0.31",
|
||||
"@types/react-dom": "^18.0.11",
|
||||
"@unocss/cli": "^0.50.6",
|
||||
"@unocss/reset": "^0.50.6",
|
||||
"@vitejs/plugin-react": "^3.1.0",
|
||||
"@vitest/coverage-c8": "^0.29.8",
|
||||
"concurrently": "^8.0.1",
|
||||
"@types/html-escaper": "^3.0.0",
|
||||
"@types/node": "18.17.1",
|
||||
"@types/react": "^18.2.17",
|
||||
"@types/react-dom": "^18.2.7",
|
||||
"@unocss/cli": "^0.54.0",
|
||||
"@unocss/eslint-config": "^0.54.0",
|
||||
"@unocss/reset": "^0.54.0",
|
||||
"@vitejs/plugin-react": "^4.0.3",
|
||||
"@vitest/coverage-c8": "^0.33.0",
|
||||
"concurrently": "^8.2.0",
|
||||
"cross-env": "^7.0.3",
|
||||
"eslint": "^8.37.0",
|
||||
"eslint-config-neon": "^0.1.41",
|
||||
"eslint": "^8.46.0",
|
||||
"eslint-config-neon": "^0.1.47",
|
||||
"eslint-formatter-pretty": "^5.0.0",
|
||||
"happy-dom": "^8.9.0",
|
||||
"happy-dom": "^10.5.2",
|
||||
"hast-util-to-string": "^2.0.0",
|
||||
"hastscript": "^7.2.0",
|
||||
"html-escaper": "^3.0.3",
|
||||
"lighthouse": "^10.1.0",
|
||||
"prettier": "^2.8.7",
|
||||
"prettier-plugin-astro": "^0.8.0",
|
||||
"prettier-plugin-tailwindcss": "^0.2.6",
|
||||
"typescript": "^5.0.3",
|
||||
"unocss": "^0.50.6",
|
||||
"vercel": "^28.18.3",
|
||||
"vitest": "^0.29.8"
|
||||
"lighthouse": "^10.4.0",
|
||||
"prettier": "^2.8.8",
|
||||
"turbo": "^1.10.12",
|
||||
"typescript": "^5.1.6",
|
||||
"unocss": "^0.54.0",
|
||||
"vercel": "^31.2.0",
|
||||
"vitest": "^0.33.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18.13.0"
|
||||
|
||||
BIN
apps/guide/public/assets/after-sorting.png
Normal file
|
After Width: | Height: | Size: 11 KiB |
BIN
apps/guide/public/assets/before-sorting.png
Normal file
|
After Width: | Height: | Size: 8.8 KiB |
BIN
apps/guide/public/assets/bot-auth-page.png
Normal file
|
After Width: | Height: | Size: 39 KiB |
BIN
apps/guide/public/assets/bot-authorized.png
Normal file
|
After Width: | Height: | Size: 13 KiB |
BIN
apps/guide/public/assets/bot-in-memberlist.png
Normal file
|
After Width: | Height: | Size: 6.6 KiB |
BIN
apps/guide/public/assets/bot-user.png
Normal file
|
After Width: | Height: | Size: 75 KiB |
BIN
apps/guide/public/assets/create-app.png
Normal file
|
After Width: | Height: | Size: 64 KiB |
BIN
apps/guide/public/assets/discordjs.png
Normal file
|
After Width: | Height: | Size: 11 KiB |
BIN
apps/guide/public/assets/integrations-tab.png
Normal file
|
After Width: | Height: | Size: 164 KiB |
BIN
apps/guide/public/assets/integrations-view-tab.png
Normal file
|
After Width: | Height: | Size: 53 KiB |
BIN
apps/guide/public/assets/old-guide.png
Executable file
|
After Width: | Height: | Size: 2.0 KiB |
BIN
apps/guide/public/assets/snek-bot.jpeg
Normal file
|
After Width: | Height: | Size: 9.0 KiB |
BIN
apps/guide/public/assets/webhook.png
Normal file
|
After Width: | Height: | Size: 76 KiB |
@@ -3,15 +3,15 @@
|
||||
import { Providers } from './providers';
|
||||
import { inter } from '~/util/fonts';
|
||||
|
||||
export default function GlobalError({ error }: { error: Error }) {
|
||||
export default function GlobalError({ error }: { readonly error: Error }) {
|
||||
console.error(error);
|
||||
|
||||
return (
|
||||
<html className={inter.variable} lang="en" suppressHydrationWarning>
|
||||
<body className="dark:bg-dark-800 bg-light-600">
|
||||
<body className="bg-light-600 dark:bg-dark-600 dark:text-light-900">
|
||||
<Providers>
|
||||
<main className="mx-auto min-h-screen max-w-2xl">
|
||||
<div className="mx-auto flex min-h-screen max-w-lg flex-col place-content-center place-items-center gap-8 px-8 py-16 lg:px-6 lg:py-0">
|
||||
<main className="mx-auto max-w-2xl min-h-screen">
|
||||
<div className="mx-auto max-w-lg min-h-screen flex flex-col place-content-center place-items-center gap-8 px-8 py-16 lg:px-6 lg:py-0">
|
||||
<h1 className="text-[9rem] font-black leading-none md:text-[12rem]">500</h1>
|
||||
<h2 className="text-[2rem] md:text-[3rem]">Error.</h2>
|
||||
</div>
|
||||
@@ -1,10 +1,10 @@
|
||||
'use client';
|
||||
|
||||
export default function Error({ error }: { error: Error }) {
|
||||
export default function Error({ error }: { readonly error: Error }) {
|
||||
console.error(error);
|
||||
|
||||
return (
|
||||
<div className="mx-auto flex h-full max-w-lg flex-col place-content-center place-items-center gap-8 px-8 py-16 lg:px-6 lg:py-0">
|
||||
<div className="mx-auto max-w-lg min-h-screen flex flex-col place-content-center place-items-center gap-8 px-8 py-16 lg:px-6 lg:py-0">
|
||||
<h1 className="text-[9rem] font-black leading-none md:text-[12rem]">500</h1>
|
||||
<h2 className="text-[2rem] md:text-[3rem]">Error.</h2>
|
||||
</div>
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { Providers } from './providers';
|
||||
import { inter } from '~/util/fonts';
|
||||
|
||||
export default function GlobalError({ error }: { error: Error }) {
|
||||
console.error(error);
|
||||
|
||||
return (
|
||||
<html className={inter.variable} lang="en" suppressHydrationWarning>
|
||||
<body className="dark:bg-dark-800 bg-light-600">
|
||||
<Providers>
|
||||
<main className="mx-auto h-screen max-w-2xl">
|
||||
<div className="mx-auto flex h-screen max-w-lg flex-col place-content-center place-items-center gap-8 px-8 py-16 lg:px-6 lg:py-0">
|
||||
<h1 className="text-[9rem] font-black leading-none md:text-[12rem]">500</h1>
|
||||
<h2 className="text-[2rem] md:text-[3rem]">Error.</h2>
|
||||
</div>
|
||||
</main>
|
||||
</Providers>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
1
apps/guide/src/app/guide/[...slug]/not-found.tsx
Normal file
@@ -0,0 +1 @@
|
||||
export { default } from '~/app/not-found';
|
||||
@@ -3,10 +3,10 @@ import { notFound } from 'next/navigation';
|
||||
import { Mdx } from '~/components/Mdx';
|
||||
|
||||
export async function generateStaticParams() {
|
||||
return allContents.map((content) => ({ slug: content.slug }));
|
||||
return allContents.map((content) => ({ slug: [content.slug] }));
|
||||
}
|
||||
|
||||
export default function Page({ params }: { params: { slug: string[] } }) {
|
||||
export default function Page({ params }: { readonly params: { slug: string[] } }) {
|
||||
const content = allContents.find((content) => content.slug === params.slug?.join('/'));
|
||||
|
||||
if (!content) {
|
||||
@@ -14,7 +14,7 @@ export default function Page({ params }: { params: { slug: string[] } }) {
|
||||
}
|
||||
|
||||
return (
|
||||
<article className="prose mx-auto max-w-4xl py-8">
|
||||
<article className="max-w-none px-5 prose">
|
||||
<Mdx code={content?.body.code ?? ''} />
|
||||
</article>
|
||||
);
|
||||
25
apps/guide/src/app/guide/layout.tsx
Normal file
@@ -0,0 +1,25 @@
|
||||
import type { PropsWithChildren } from 'react';
|
||||
import { Providers } from './providers';
|
||||
import Footer from '~/components/Footer';
|
||||
import Header from '~/components/Header';
|
||||
import { Nav } from '~/components/Nav';
|
||||
|
||||
export default function Layout({ children }: PropsWithChildren) {
|
||||
return (
|
||||
<Providers>
|
||||
<main className="mx-auto max-w-7xl px-4 lg:max-w-full">
|
||||
<Header />
|
||||
<div className="relative top-6 mx-auto max-w-7xl gap-6 lg:max-w-full lg:flex">
|
||||
<div className="lg:sticky lg:top-23 lg:h-[calc(100vh_-_105px)]">
|
||||
<Nav />
|
||||
</div>
|
||||
|
||||
<div className="mx-auto max-w-5xl min-w-xs w-full pb-10">
|
||||
{children}
|
||||
<Footer />
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
</Providers>
|
||||
);
|
||||
}
|
||||
3
apps/guide/src/app/guide/page.tsx
Normal file
@@ -0,0 +1,3 @@
|
||||
export default function Page() {
|
||||
return null;
|
||||
}
|
||||
8
apps/guide/src/app/guide/providers.tsx
Normal file
@@ -0,0 +1,8 @@
|
||||
'use client';
|
||||
|
||||
import type { PropsWithChildren } from 'react';
|
||||
import { NavProvider } from '~/contexts/nav';
|
||||
|
||||
export function Providers({ children }: PropsWithChildren) {
|
||||
return <NavProvider>{children}</NavProvider>;
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Analytics } from '@vercel/analytics/react';
|
||||
import type { Metadata } from 'next/types';
|
||||
import type { Metadata } from 'next';
|
||||
import type { PropsWithChildren } from 'react';
|
||||
import { Providers } from './providers';
|
||||
import { DESCRIPTION } from '~/util/constants';
|
||||
@@ -44,7 +44,10 @@ export const metadata: Metadata = {
|
||||
|
||||
manifest: '/site.webmanifest',
|
||||
|
||||
themeColor: '#5865f2',
|
||||
themeColor: [
|
||||
{ media: '(prefers-color-scheme: light)', color: '#f1f3f5' },
|
||||
{ media: '(prefers-color-scheme: dark)', color: '#181818' },
|
||||
],
|
||||
colorScheme: 'light dark',
|
||||
|
||||
appleWebApp: {
|
||||
@@ -74,7 +77,7 @@ export const metadata: Metadata = {
|
||||
export default function RootLayout({ children }: PropsWithChildren) {
|
||||
return (
|
||||
<html className={`${inter.variable} ${jetBrainsMono.variable}`} lang="en" suppressHydrationWarning>
|
||||
<body className="dark:bg-dark-800 bg-light-600">
|
||||
<body className="bg-light-600 dark:bg-dark-600 dark:text-light-900">
|
||||
<Providers>{children}</Providers>
|
||||
<Analytics />
|
||||
</body>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
export default function Loading() {
|
||||
return (
|
||||
<div className="mx-4 flex min-h-screen flex-col items-center justify-center gap-4">
|
||||
<div className="mx-4 min-h-screen flex flex-col items-center justify-center gap-4">
|
||||
<svg
|
||||
className="h-9 w-9 animate-spin text-black dark:text-white"
|
||||
fill="none"
|
||||
|
||||
@@ -2,12 +2,12 @@ import Link from 'next/link';
|
||||
|
||||
export default function NotFound() {
|
||||
return (
|
||||
<div className="mx-auto flex min-h-screen max-w-lg flex-col place-content-center place-items-center gap-8 px-8 py-16 lg:px-6 lg:py-0">
|
||||
<div className="mx-auto max-w-lg min-h-screen flex flex-col place-content-center place-items-center gap-8 px-8 py-16 lg:px-6 lg:py-0">
|
||||
<h1 className="text-[9rem] font-black leading-none md:text-[12rem]">404</h1>
|
||||
<h2 className="text-[2rem] md:text-[3rem]">Not found.</h2>
|
||||
<Link
|
||||
className="bg-blurple focus:ring-width-2 flex h-11 transform-gpu cursor-pointer select-none appearance-none flex-row place-items-center rounded border-0 px-6 text-base font-semibold leading-none text-white no-underline outline-0 focus:ring focus:ring-white active:translate-y-px"
|
||||
href="/docs/packages"
|
||||
className="h-11 flex flex-row transform-gpu cursor-pointer select-none appearance-none place-items-center border-0 rounded bg-blurple px-6 text-base font-semibold leading-none text-white no-underline outline-none active:translate-y-px focus:ring focus:ring-width-2 focus:ring-white"
|
||||
href="/guide"
|
||||
>
|
||||
Take me back
|
||||
</Link>
|
||||
|
||||
@@ -1,26 +1,3 @@
|
||||
import Image from 'next/image';
|
||||
import vercelLogo from '~/assets/powered-by-vercel.svg';
|
||||
|
||||
export default function Page() {
|
||||
return (
|
||||
<div className="mx-auto flex min-h-screen max-w-6xl flex-col place-items-center gap-12 px-8 py-16 lg:place-content-center lg:px-8 lg:py-0">
|
||||
<div className="flex flex-row place-content-center">
|
||||
<a
|
||||
className="focus:ring-width-2 focus:ring-blurple rounded outline-0 focus:ring"
|
||||
href="https://vercel.com/?utm_source=discordjs&utm_campaign=oss"
|
||||
rel="noopener noreferrer"
|
||||
target="_blank"
|
||||
title="Vercel"
|
||||
>
|
||||
<Image
|
||||
alt="Vercel"
|
||||
blurDataURL="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAABLCAQAAAA1k5H2AAAAi0lEQVR42u3SMQEAAAgDoC251a3gL2SgmfBYBRAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARCAgwWEOSWBnYbKggAAAABJRU5ErkJggg=="
|
||||
placeholder="blur"
|
||||
priority
|
||||
src={vercelLogo}
|
||||
/>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
BIN
apps/guide/src/assets/powered-by-workers.png
Normal file
|
After Width: | Height: | Size: 16 KiB |
91
apps/guide/src/components/DiscordAPITypesLink.tsx
Normal file
@@ -0,0 +1,91 @@
|
||||
import { FiExternalLink } from '@react-icons/all-files/fi/FiExternalLink';
|
||||
import type { PropsWithChildren } from 'react';
|
||||
import {
|
||||
BASE_URL_DISCORD_API_TYPES,
|
||||
DISCORD_API_TYPES_VERSION,
|
||||
DISCORD_API_TYPES_VOICE_VERSION,
|
||||
} from '~/util/constants';
|
||||
|
||||
interface DiscordAPITypesLinkOptions {
|
||||
/**
|
||||
* The initial documentation enum, interface, function etc.
|
||||
*
|
||||
* @example `'RESTJSONErrorCodes'`
|
||||
*/
|
||||
readonly parent?: string;
|
||||
/**
|
||||
* The scope of where this link lives.
|
||||
*
|
||||
* @remarks API does not have a scope.
|
||||
*/
|
||||
readonly scope?: 'gateway' | 'globals' | 'payloads' | 'rest' | 'rpc' | 'utils' | 'voice';
|
||||
/**
|
||||
* The symbol belonging to the parent.
|
||||
*
|
||||
* @example '`MaximumNumberOfGuildsReached'`
|
||||
*/
|
||||
readonly symbol?: string;
|
||||
/**
|
||||
* The type of the {@link DiscordAPITypesLinkOptions.parent}.
|
||||
*
|
||||
* @example `'enum'`
|
||||
* @example `'interface'`
|
||||
*/
|
||||
readonly type?: string;
|
||||
}
|
||||
|
||||
export function DiscordAPITypesLink({
|
||||
parent,
|
||||
scope,
|
||||
symbol,
|
||||
type,
|
||||
children,
|
||||
}: PropsWithChildren<DiscordAPITypesLinkOptions>) {
|
||||
let url = BASE_URL_DISCORD_API_TYPES;
|
||||
let text = 'discord-api-types';
|
||||
|
||||
if (type || parent) {
|
||||
url += `/api/discord-api-types`;
|
||||
|
||||
switch (scope) {
|
||||
case 'globals':
|
||||
url += `-${scope}`;
|
||||
break;
|
||||
case 'gateway':
|
||||
case 'payloads':
|
||||
case 'rest':
|
||||
url += `-${scope}/common`;
|
||||
break;
|
||||
case 'rpc':
|
||||
case 'utils':
|
||||
url += `-${scope}/${DISCORD_API_TYPES_VERSION}`;
|
||||
break;
|
||||
case 'voice':
|
||||
url += `-${scope}/${DISCORD_API_TYPES_VOICE_VERSION}`;
|
||||
break;
|
||||
default:
|
||||
url += `-${DISCORD_API_TYPES_VERSION}`;
|
||||
}
|
||||
|
||||
if (type) {
|
||||
url += `/${type}/${parent}`;
|
||||
if (symbol) url += `#${symbol}`;
|
||||
} else {
|
||||
url += `#${parent}`;
|
||||
}
|
||||
|
||||
text = `${parent}${symbol ? `#${symbol}` : ''}${type?.toUpperCase() === 'FUNCTION' ? '()' : ''}`;
|
||||
}
|
||||
|
||||
return (
|
||||
<a
|
||||
className="inline-flex flex-row place-items-center gap-1"
|
||||
href={url}
|
||||
rel="external noopener noreferrer"
|
||||
target="_blank"
|
||||
>
|
||||
{children ?? text}
|
||||
<FiExternalLink size={18} />
|
||||
</a>
|
||||
);
|
||||
}
|
||||
@@ -1,3 +1,86 @@
|
||||
export function DocsLink() {
|
||||
return null;
|
||||
import { FiExternalLink } from '@react-icons/all-files/fi/FiExternalLink';
|
||||
import type { PropsWithChildren } from 'react';
|
||||
import { BASE_URL, BASE_URL_LEGACY, PACKAGES, VERSION } from '~/util/constants';
|
||||
|
||||
interface DocsLinkOptions {
|
||||
/**
|
||||
* Whether to apply brackets to the end of the symbol to denote a method.
|
||||
*
|
||||
* @remarks Functions automatically infer this.
|
||||
*/
|
||||
readonly brackets?: boolean;
|
||||
/**
|
||||
* The package.
|
||||
*
|
||||
* @defaultValue `'discord.js'`
|
||||
*/
|
||||
readonly package?: (typeof PACKAGES)[number];
|
||||
/**
|
||||
* The initial documentation class, function, interface etc.
|
||||
*
|
||||
* @example `'Client'`
|
||||
*/
|
||||
readonly parent?: string;
|
||||
/**
|
||||
* Whether to reference a static property.
|
||||
*
|
||||
* @remarks
|
||||
* This should only be used for the https://discord.js.org domain
|
||||
* as static properties are not identified in the URL.
|
||||
*/
|
||||
readonly static?: boolean;
|
||||
/**
|
||||
* The symbol belonging to the parent.
|
||||
*
|
||||
* @example '`login'`
|
||||
*/
|
||||
readonly symbol?: string;
|
||||
/**
|
||||
* The type of the {@link DocsLinkOptions.parent}.
|
||||
*
|
||||
* @example `'class'`
|
||||
* @example `'Function'`
|
||||
*/
|
||||
readonly type?: string;
|
||||
}
|
||||
|
||||
export function DocsLink({
|
||||
package: docs = PACKAGES[0],
|
||||
type,
|
||||
parent,
|
||||
symbol,
|
||||
brackets,
|
||||
static: staticReference,
|
||||
children,
|
||||
}: PropsWithChildren<DocsLinkOptions>) {
|
||||
// In the case of no type and no parent, this will default to the entry point of the respective documentation.
|
||||
let url = docs === PACKAGES[0] ? `${BASE_URL_LEGACY}/${VERSION}/general/welcome` : `${BASE_URL}/${docs}/stable`;
|
||||
let text = `${docs === PACKAGES[0] ? '' : '@discordjs/'}${docs}`;
|
||||
|
||||
// If there is a type and parent, we need to do some parsing.
|
||||
if (type && parent) {
|
||||
const bracketText = brackets || type?.toUpperCase() === 'FUNCTION' ? '()' : '';
|
||||
|
||||
// Legacy discord.js documentation parsing.
|
||||
if (docs === PACKAGES[0]) {
|
||||
url = `${BASE_URL_LEGACY}/${VERSION}/${type}/${parent}`;
|
||||
if (symbol) url += `?scrollTo=${symbol}`;
|
||||
|
||||
text = `${parent}${symbol ? (symbol.startsWith('s-') ? '.' : '#') : ''}${
|
||||
// eslint-disable-next-line prefer-named-capture-group
|
||||
symbol ? `${symbol.replace(/(e|s)-/, '')}` : ''
|
||||
}${bracketText}`;
|
||||
} else {
|
||||
url += `/${parent}:${type}`;
|
||||
if (symbol) url += `#${symbol}`;
|
||||
text = `${parent}${symbol ? `${staticReference ? '.' : '#'}${symbol}` : ''}${bracketText}`;
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<a className="inline-flex flex-row place-items-center gap-1" href={url} rel="noopener noreferrer" target="_blank">
|
||||
{children ?? text}
|
||||
<FiExternalLink size={18} />
|
||||
</a>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
import { FiExternalLink } from 'react-icons/fi';
|
||||
|
||||
export function ExternalLink({ href, title }: { href: string; title: string }) {
|
||||
return (
|
||||
<a className="text-blurple inline-flex place-items-center gap-2 text-sm font-semibold" href={href}>
|
||||
<p>{title}</p>
|
||||
<FiExternalLink size={18} />
|
||||
</a>
|
||||
);
|
||||
}
|
||||
98
apps/guide/src/components/Footer.tsx
Normal file
@@ -0,0 +1,98 @@
|
||||
import Image from 'next/image';
|
||||
import vercelLogo from '~/assets/powered-by-vercel.svg';
|
||||
import workersLogo from '~/assets/powered-by-workers.png';
|
||||
|
||||
export default function Footer() {
|
||||
return (
|
||||
<footer className="md:pl-12 md:pr-12">
|
||||
<div className="flex flex-col flex-wrap place-content-center gap-6 pt-12 sm:flex-row md:gap-12">
|
||||
<div className="flex flex-wrap place-content-center place-items-center gap-4">
|
||||
<a
|
||||
className="rounded outline-none focus:ring focus:ring-width-2 focus:ring-blurple"
|
||||
href="https://vercel.com/?utm_source=discordjs&utm_campaign=oss"
|
||||
rel="external noopener noreferrer"
|
||||
target="_blank"
|
||||
title="Vercel"
|
||||
>
|
||||
<Image
|
||||
alt="Vercel"
|
||||
blurDataURL="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAABLCAQAAAA1k5H2AAAAi0lEQVR42u3SMQEAAAgDoC251a3gL2SgmfBYBRAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARCAgwWEOSWBnYbKggAAAABJRU5ErkJggg=="
|
||||
height={44}
|
||||
placeholder="blur"
|
||||
src={vercelLogo}
|
||||
width={212}
|
||||
/>
|
||||
</a>
|
||||
<a
|
||||
className="rounded outline-none focus:ring focus:ring-width-2 focus:ring-blurple"
|
||||
href="https://www.cloudflare.com"
|
||||
rel="external noopener noreferrer"
|
||||
target="_blank"
|
||||
title="Cloudflare Workers"
|
||||
>
|
||||
<Image
|
||||
alt="Cloudflare"
|
||||
blurDataURL="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAABLCAQAAAA1k5H2AAAAi0lEQVR42u3SMQEAAAgDoC251a3gL2SgmfBYBRAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARAAARCAgwWEOSWBnYbKggAAAABJRU5ErkJggg=="
|
||||
height={44}
|
||||
placeholder="blur"
|
||||
priority
|
||||
src={workersLogo}
|
||||
/>
|
||||
</a>
|
||||
</div>
|
||||
<div className="flex flex-col place-self-center gap-6 sm:flex-row md:gap-12">
|
||||
<div className="max-w-max flex flex-col gap-2">
|
||||
<div className="text-lg font-semibold">Community</div>
|
||||
<div className="flex flex-col gap-1">
|
||||
<a
|
||||
className="rounded outline-none focus:ring focus:ring-width-2 focus:ring-blurple"
|
||||
href="https://discord.gg/djs"
|
||||
rel="external noopener noreferrer"
|
||||
target="_blank"
|
||||
>
|
||||
Discord
|
||||
</a>
|
||||
<a
|
||||
className="rounded outline-none focus:ring focus:ring-width-2 focus:ring-blurple"
|
||||
href="https://github.com/discordjs/discord.js/discussions"
|
||||
rel="external noopener noreferrer"
|
||||
target="_blank"
|
||||
>
|
||||
GitHub discussions
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
<div className="max-w-max flex flex-col gap-2">
|
||||
<div className="text-lg font-semibold">Project</div>
|
||||
<div className="flex flex-col gap-1">
|
||||
<a
|
||||
className="rounded outline-none focus:ring focus:ring-width-2 focus:ring-blurple"
|
||||
href="https://github.com/discordjs/discord.js"
|
||||
rel="external noopener noreferrer"
|
||||
target="_blank"
|
||||
>
|
||||
discord.js
|
||||
</a>
|
||||
<a
|
||||
className="rounded outline-none focus:ring focus:ring-width-2 focus:ring-blurple"
|
||||
href="https://discord.js.org/docs"
|
||||
rel="noopener noreferrer"
|
||||
target="_blank"
|
||||
>
|
||||
discord.js documentation
|
||||
</a>
|
||||
<a
|
||||
className="rounded outline-none focus:ring focus:ring-width-2 focus:ring-blurple"
|
||||
href="https://discord-api-types.dev"
|
||||
rel="external noopener noreferrer"
|
||||
target="_blank"
|
||||
>
|
||||
discord-api-types
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</footer>
|
||||
);
|
||||
}
|
||||
9
apps/guide/src/components/H1.tsx
Normal file
@@ -0,0 +1,9 @@
|
||||
import type { HTMLAttributes, PropsWithChildren } from 'react';
|
||||
|
||||
export function H1({ children, className, ...props }: PropsWithChildren<HTMLAttributes<HTMLHeadingElement>>) {
|
||||
return (
|
||||
<h1 className={`group ${className}`} {...props}>
|
||||
{children}
|
||||
</h1>
|
||||
);
|
||||
}
|
||||
9
apps/guide/src/components/H2.tsx
Normal file
@@ -0,0 +1,9 @@
|
||||
import type { HTMLAttributes, PropsWithChildren } from 'react';
|
||||
|
||||
export function H2({ children, className, ...props }: PropsWithChildren<HTMLAttributes<HTMLHeadingElement>>) {
|
||||
return (
|
||||
<h2 className={`group ${className}`} {...props}>
|
||||
{children}
|
||||
</h2>
|
||||
);
|
||||
}
|
||||
9
apps/guide/src/components/H3.tsx
Normal file
@@ -0,0 +1,9 @@
|
||||
import type { HTMLAttributes, PropsWithChildren } from 'react';
|
||||
|
||||
export function H3({ children, className, ...props }: PropsWithChildren<HTMLAttributes<HTMLHeadingElement>>) {
|
||||
return (
|
||||
<h3 className={`group ${className}`} {...props}>
|
||||
{children}
|
||||
</h3>
|
||||
);
|
||||
}
|
||||
9
apps/guide/src/components/H4.tsx
Normal file
@@ -0,0 +1,9 @@
|
||||
import type { HTMLAttributes, PropsWithChildren } from 'react';
|
||||
|
||||
export function H4({ children, className, ...props }: PropsWithChildren<HTMLAttributes<HTMLHeadingElement>>) {
|
||||
return (
|
||||
<h4 className={`group ${className}`} {...props}>
|
||||
{children}
|
||||
</h4>
|
||||
);
|
||||
}
|
||||
91
apps/guide/src/components/Header.tsx
Normal file
@@ -0,0 +1,91 @@
|
||||
'use client';
|
||||
|
||||
import { VscGithubInverted } from '@react-icons/all-files/vsc/VscGithubInverted';
|
||||
import { VscMenu } from '@react-icons/all-files/vsc/VscMenu';
|
||||
import { Button } from 'ariakit/button';
|
||||
import dynamic from 'next/dynamic';
|
||||
import Link from 'next/link';
|
||||
import { usePathname } from 'next/navigation';
|
||||
import { Fragment, useMemo } from 'react';
|
||||
import { useNav } from '~/contexts/nav';
|
||||
|
||||
const ThemeSwitcher = dynamic(async () => import('./ThemeSwitcher'));
|
||||
|
||||
export default function Header() {
|
||||
const pathname = usePathname();
|
||||
const { setOpened } = useNav();
|
||||
|
||||
const pathElements = useMemo(
|
||||
() =>
|
||||
pathname
|
||||
.split('/')
|
||||
.slice(1)
|
||||
.map((path, idx, original) => (
|
||||
<Link
|
||||
className="rounded outline-none hover:underline focus:ring focus:ring-width-2 focus:ring-blurple"
|
||||
href={`/${original.slice(0, idx + 1).join('/')}`}
|
||||
key={`${path}-${idx}`}
|
||||
>
|
||||
{path}
|
||||
</Link>
|
||||
)),
|
||||
[pathname],
|
||||
);
|
||||
|
||||
const breadcrumbs = useMemo(
|
||||
() =>
|
||||
pathElements.flatMap((el, idx, array) => {
|
||||
if (idx === 0) {
|
||||
return (
|
||||
<Fragment key={`${el.key}-${idx}`}>
|
||||
<div className="mx-2">/</div>
|
||||
<div>{el}</div>
|
||||
<div className="mx-2">/</div>
|
||||
</Fragment>
|
||||
);
|
||||
}
|
||||
|
||||
if (idx !== array.length - 1) {
|
||||
return (
|
||||
<Fragment key={`${el.key}-${idx}`}>
|
||||
<div>{el}</div>
|
||||
<div className="mx-2">/</div>
|
||||
</Fragment>
|
||||
);
|
||||
}
|
||||
|
||||
return <div key={`${el.key}-${idx}`}>{el}</div>;
|
||||
}),
|
||||
[pathElements],
|
||||
);
|
||||
|
||||
return (
|
||||
<header className="sticky top-4 z-20 border border-light-900 rounded-md bg-white/75 shadow backdrop-blur-md dark:border-dark-100 dark:bg-dark-600/75">
|
||||
<div className="block h-16 px-6">
|
||||
<div className="h-full flex flex-row place-content-between place-items-center gap-8">
|
||||
<Button
|
||||
aria-label="Menu"
|
||||
className="h-6 w-6 flex flex-row transform-gpu cursor-pointer select-none appearance-none place-items-center border-0 rounded bg-transparent p-0 text-sm font-semibold leading-none no-underline outline-none lg:hidden active:translate-y-px focus:ring focus:ring-width-2 focus:ring-blurple"
|
||||
onClick={() => setOpened((open) => !open)}
|
||||
>
|
||||
<VscMenu size={24} />
|
||||
</Button>
|
||||
<div className="hidden lg:flex lg:grow lg:flex-row lg:overflow-hidden">{breadcrumbs}</div>
|
||||
<div className="flex flex-row place-items-center gap-4">
|
||||
<Button
|
||||
aria-label="GitHub"
|
||||
as="a"
|
||||
className="h-6 w-6 flex flex-row transform-gpu cursor-pointer select-none appearance-none place-items-center border-0 rounded rounded-full bg-transparent p-0 text-sm font-semibold leading-none no-underline outline-none active:translate-y-px focus:ring focus:ring-width-2 focus:ring-blurple"
|
||||
href="https://github.com/discordjs/discord.js"
|
||||
rel="external noopener noreferrer"
|
||||
target="_blank"
|
||||
>
|
||||
<VscGithubInverted size={24} />
|
||||
</Button>
|
||||
<ThemeSwitcher />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
@@ -2,15 +2,33 @@
|
||||
|
||||
import { Alert, Section, DiscordMessages, DiscordMessage, DiscordMessageEmbed } from '@discordjs/ui';
|
||||
import { useMDXComponent } from 'next-contentlayer/hooks';
|
||||
import { DiscordAPITypesLink } from './DiscordAPITypesLink';
|
||||
import { H1 } from './H1';
|
||||
import { H2 } from './H2';
|
||||
import { H3 } from './H3';
|
||||
import { H4 } from './H4';
|
||||
import { DocsLink } from '~/components/DocsLink';
|
||||
import { ResultingCode } from '~/components/ResultingCode';
|
||||
|
||||
export function Mdx({ code }: { code: string }) {
|
||||
export function Mdx({ code }: { readonly code: string }) {
|
||||
const Component = useMDXComponent(code);
|
||||
|
||||
return (
|
||||
<Component
|
||||
components={{ Alert, Section, DiscordMessages, DiscordMessage, DiscordMessageEmbed, DocsLink, ResultingCode }}
|
||||
components={{
|
||||
Alert,
|
||||
Section,
|
||||
DiscordMessages,
|
||||
DiscordMessage,
|
||||
DiscordMessageEmbed,
|
||||
DiscordAPITypesLink,
|
||||
DocsLink,
|
||||
ResultingCode,
|
||||
h1: H1,
|
||||
h2: H2,
|
||||
h3: H3,
|
||||
h4: H4,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
30
apps/guide/src/components/Nav.tsx
Normal file
@@ -0,0 +1,30 @@
|
||||
'use client';
|
||||
|
||||
import { Scrollbars } from 'react-custom-scrollbars-2';
|
||||
import { Sidebar } from './Sidebar';
|
||||
import { useNav } from '~/contexts/nav';
|
||||
|
||||
export function Nav() {
|
||||
const { opened } = useNav();
|
||||
|
||||
return (
|
||||
<nav
|
||||
className={`dark:bg-dark-600/75 dark:border-dark-100 border-light-900 top-22 fixed bottom-4 left-4 right-4 z-20 mx-auto max-w-5xl rounded-md border bg-white/75 shadow backdrop-blur-md ${
|
||||
opened ? 'block' : 'hidden'
|
||||
} lg:min-w-xs lg:sticky lg:block lg:h-full lg:w-full lg:max-w-xs`}
|
||||
>
|
||||
<Scrollbars
|
||||
autoHide
|
||||
className="[&>div]:overscroll-none"
|
||||
hideTracksWhenNotNeeded
|
||||
renderThumbVertical={(props) => <div {...props} className="z-30 rounded bg-light-900 dark:bg-dark-100" />}
|
||||
renderTrackVertical={(props) => (
|
||||
<div {...props} className="absolute bottom-0.5 right-0.5 top-0.5 z-30 w-1.5 rounded" />
|
||||
)}
|
||||
universal
|
||||
>
|
||||
<Sidebar />
|
||||
</Scrollbars>
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
import { Button } from 'ariakit/button';
|
||||
import { useState, useEffect } from 'react';
|
||||
import { FiCommand } from 'react-icons/fi';
|
||||
import { VscColorMode, VscGithubInverted, VscMenu, VscSearch } from 'react-icons/vsc';
|
||||
import { useMedia } from 'react-use';
|
||||
import { Sidebar } from './Sidebar.jsx';
|
||||
import type { MDXPage } from './SidebarItems.jsx';
|
||||
|
||||
export function Navbar({ pages }: { pages?: MDXPage[] | undefined }) {
|
||||
const matches = useMedia('(min-width: 992px)', false);
|
||||
const [opened, setOpened] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (matches) {
|
||||
setOpened(false);
|
||||
}
|
||||
}, [matches]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<header className="dark:bg-dark-400 dark:border-dark-100 bg-light-600 border-light-800 fixed left-0 top-0 z-20 w-full border-b">
|
||||
<div className="block h-16 px-6">
|
||||
<div className="flex h-full flex-row place-content-between place-items-center">
|
||||
<Button
|
||||
aria-label="Menu"
|
||||
className="focus:ring-width-2 focus:ring-blurple flex h-6 w-6 transform-gpu cursor-pointer select-none appearance-none place-items-center rounded border-0 bg-transparent p-0 text-sm font-semibold leading-none no-underline outline-0 focus:ring active:translate-y-px lg:hidden"
|
||||
onClick={() => setOpened((open) => !open)}
|
||||
>
|
||||
<VscMenu size={24} />
|
||||
</Button>
|
||||
<div className="hidden md:flex md:flex-row">Placeholder</div>
|
||||
<div className="flex flex-row place-items-center gap-4">
|
||||
<Button
|
||||
as="div"
|
||||
className="dark:bg-dark-800 focus:ring-width-2 focus:ring-blurple rounded bg-white px-4 py-2.5 outline-0 focus:ring"
|
||||
// onClick={() => dialog?.toggle()}
|
||||
>
|
||||
<div className="flex flex-row place-items-center gap-4">
|
||||
<VscSearch size={18} />
|
||||
<span className="opacity-65">Search...</span>
|
||||
<div className="opacity-65 flex flex-row place-items-center gap-2">
|
||||
<FiCommand size={18} /> K
|
||||
</div>
|
||||
</div>
|
||||
</Button>
|
||||
<Button
|
||||
aria-label="GitHub"
|
||||
as="a"
|
||||
className="focus:ring-width-2 focus:ring-blurple flex h-6 w-6 transform-gpu cursor-pointer select-none appearance-none place-items-center rounded rounded-full border-0 bg-transparent p-0 text-sm font-semibold leading-none no-underline outline-0 focus:ring active:translate-y-px"
|
||||
href="https://github.com/discordjs/discord.js"
|
||||
rel="noopener noreferrer"
|
||||
target="_blank"
|
||||
>
|
||||
<VscGithubInverted size={24} />
|
||||
</Button>
|
||||
<Button
|
||||
aria-label="Toggle theme"
|
||||
className="focus:ring-width-2 focus:ring-blurple flex h-6 w-6 transform-gpu cursor-pointer select-none appearance-none place-items-center rounded rounded-full border-0 bg-transparent p-0 text-sm font-semibold leading-none no-underline outline-0 focus:ring active:translate-y-px"
|
||||
// onClick={() => toggleTheme()}
|
||||
>
|
||||
<VscColorMode size={24} />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
<Sidebar opened={opened} pages={pages} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,22 +1,19 @@
|
||||
import type { MarkdownHeading } from 'astro';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { useMemo, useState } from 'react';
|
||||
import { Scrollbars } from 'react-custom-scrollbars-2';
|
||||
import { VscListSelection } from 'react-icons/vsc';
|
||||
import { useLocation } from 'react-use';
|
||||
|
||||
const LINK_HEIGHT = 30;
|
||||
const INDICATOR_SIZE = 10;
|
||||
const INDICATOR_OFFSET = (LINK_HEIGHT - INDICATOR_SIZE) / 2;
|
||||
|
||||
export function Outline({ headings }: { headings: MarkdownHeading[] }) {
|
||||
const state = useLocation();
|
||||
const [active, setActive] = useState(0);
|
||||
export function Outline({ headings }: { readonly headings: any[] }) {
|
||||
// eslint-disable-next-line react/hook-use-state
|
||||
const [active /* setActive */] = useState(0);
|
||||
|
||||
const headingItems = useMemo(
|
||||
() =>
|
||||
headings.map((heading, idx) => (
|
||||
<a
|
||||
className={`dark:border-dark-100 border-light-800 pl-6.5 focus:ring-width-2 focus:ring-blurple ml-[10px] border-l p-[5px] text-sm outline-0 focus:rounded focus:border-0 focus:ring ${
|
||||
className={`dark:border-dark-100 border-light-800 pl-6.5 focus:ring-width-2 focus:ring-blurple ml-[10px] border-l p-[5px] text-sm outline-none focus:rounded focus:border-0 focus:ring ${
|
||||
idx === active
|
||||
? 'bg-blurple text-white'
|
||||
: 'dark:hover:bg-dark-200 dark:active:bg-dark-100 hover:bg-light-700 active:bg-light-800'
|
||||
@@ -32,18 +29,18 @@ export function Outline({ headings }: { headings: MarkdownHeading[] }) {
|
||||
[headings, active],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const idx = headings.findIndex((heading) => heading.slug === state.hash?.slice(1));
|
||||
if (idx >= 0) {
|
||||
setActive(idx);
|
||||
}
|
||||
}, [state, headings]);
|
||||
// useEffect(() => {
|
||||
// const idx = headings.findIndex((heading) => heading.slug === state.hash?.slice(1));
|
||||
// if (idx >= 0) {
|
||||
// setActive(idx);
|
||||
// }
|
||||
// }, [state, headings]);
|
||||
|
||||
return (
|
||||
<Scrollbars
|
||||
autoHide
|
||||
hideTracksWhenNotNeeded
|
||||
renderThumbVertical={(props) => <div {...props} className="dark:bg-dark-100 bg-light-900 z-30 rounded" />}
|
||||
renderThumbVertical={(props) => <div {...props} className="z-30 rounded bg-light-900 dark:bg-dark-100" />}
|
||||
renderTrackVertical={(props) => (
|
||||
<div {...props} className="absolute bottom-0.5 right-0.5 top-0.5 z-30 w-1.5 rounded" />
|
||||
)}
|
||||
@@ -51,13 +48,13 @@ export function Outline({ headings }: { headings: MarkdownHeading[] }) {
|
||||
>
|
||||
<div className="flex flex-col break-all p-3 pb-8">
|
||||
<div className="ml-2 mt-4 flex flex-row gap-2">
|
||||
<VscListSelection size={25} />
|
||||
{/* <VscListSelection size={25} /> */}
|
||||
<span className="font-semibold">Contents</span>
|
||||
</div>
|
||||
<div className="ml-2 mt-4 flex flex-col gap-2">
|
||||
<div className="relative flex flex-col">
|
||||
<div
|
||||
className="bg-blurple absolute h-[10px] w-[10px] rounded-full border-2 border-black dark:border-white"
|
||||
className="absolute h-[10px] w-[10px] border-2 border-black rounded-full bg-blurple dark:border-white"
|
||||
style={{
|
||||
left: INDICATOR_SIZE / 2 + 0.5,
|
||||
transform: `translateY(${active * LINK_HEIGHT + INDICATOR_OFFSET}px)`,
|
||||
|
||||
@@ -1,7 +1,15 @@
|
||||
export function PageButton({ url, title, direction }: { direction: 'next' | 'prev'; title: string; url: string }) {
|
||||
export function PageButton({
|
||||
url,
|
||||
title,
|
||||
direction,
|
||||
}: {
|
||||
readonly direction: 'next' | 'prev';
|
||||
readonly title: string;
|
||||
readonly url: string;
|
||||
}) {
|
||||
return (
|
||||
<a
|
||||
className="bg-light-600 hover:bg-light-700 active:bg-light-800 dark:bg-dark-600 dark:hover:bg-dark-500 dark:active:bg-dark-400 focus:ring-width-2 focus:ring-blurple flex transform-gpu cursor-pointer select-none appearance-none flex-row flex-col place-items-center gap-2 rounded px-4 py-3 leading-none no-underline outline-0 focus:ring active:translate-y-px"
|
||||
className="flex flex-row flex-col transform-gpu cursor-pointer select-none appearance-none place-items-center gap-2 rounded bg-light-600 px-4 py-3 leading-none no-underline outline-none active:translate-y-px active:bg-light-800 dark:bg-dark-600 hover:bg-light-700 focus:ring focus:ring-width-2 focus:ring-blurple dark:active:bg-dark-400 dark:hover:bg-dark-500"
|
||||
href={url}
|
||||
>
|
||||
<h3 className="text-md font-semibold">{title}</h3>
|
||||
|
||||
8
apps/guide/src/components/Section.tsx
Normal file
@@ -0,0 +1,8 @@
|
||||
'use client';
|
||||
|
||||
import { Section as DJSSection, type SectionOptions } from '@discordjs/ui';
|
||||
import type { PropsWithChildren } from 'react';
|
||||
|
||||
export function Section(options: PropsWithChildren<SectionOptions>) {
|
||||
return <DJSSection {...options} />;
|
||||
}
|
||||
@@ -1,24 +1,62 @@
|
||||
import { Scrollbars } from 'react-custom-scrollbars-2';
|
||||
import type { MDXPage } from './SidebarItems.jsx';
|
||||
'use client';
|
||||
|
||||
import { allContents } from 'contentlayer/generated';
|
||||
import Link from 'next/link';
|
||||
import { usePathname } from 'next/navigation';
|
||||
import { Section } from './Section';
|
||||
import { useNav } from '~/contexts/nav';
|
||||
|
||||
const items = allContents.map((content) => ({
|
||||
title: content.title,
|
||||
category: content.category,
|
||||
slug: content.slug,
|
||||
href: content.url,
|
||||
}));
|
||||
|
||||
function transformItemsByCategory(allContents: typeof items) {
|
||||
return allContents.reduce<Record<string, typeof items>>((accumulator: any, content) => {
|
||||
if (!accumulator[content.category]) {
|
||||
accumulator[content.category] = [];
|
||||
}
|
||||
|
||||
accumulator[content.category].push(content);
|
||||
return accumulator;
|
||||
}, {});
|
||||
}
|
||||
|
||||
const itemsByCategory = transformItemsByCategory(items);
|
||||
|
||||
export function Sidebar() {
|
||||
const pathname = usePathname();
|
||||
const { setOpened } = useNav();
|
||||
|
||||
export function Sidebar({ pages, opened }: { opened: boolean; pages?: MDXPage[] | undefined }) {
|
||||
return (
|
||||
<nav
|
||||
className={`h-[calc(100vh - 65px)] dark:bg-dark-600 dark:border-dark-100 border-light-800 fixed bottom-0 left-0 top-[65px] z-20 w-full border-r bg-white ${
|
||||
opened ? 'block' : 'hidden'
|
||||
} lg:w-76 lg:max-w-76 lg:block`}
|
||||
>
|
||||
<Scrollbars
|
||||
autoHide
|
||||
hideTracksWhenNotNeeded
|
||||
renderThumbVertical={(props) => <div {...props} className="dark:bg-dark-100 bg-light-900 z-30 rounded" />}
|
||||
renderTrackVertical={(props) => (
|
||||
<div {...props} className="absolute bottom-0.5 right-0.5 top-0.5 z-30 w-1.5 rounded" />
|
||||
)}
|
||||
universal
|
||||
>
|
||||
{pages ?? null}
|
||||
</Scrollbars>
|
||||
</nav>
|
||||
<div className="flex flex-col gap-3 p-3">
|
||||
{Object.keys(itemsByCategory).map((category, idx) => (
|
||||
<Section
|
||||
buttonClassName="bg-light-600 hover:bg-light-700 active:bg-light-800 dark:bg-dark-400 dark:hover:bg-dark-300 dark:active:bg-dark-400 focus:ring-width-2 focus:ring-blurple rounded p-3 outline-none focus:ring z-10"
|
||||
key={`${category}-${idx}`}
|
||||
title={category}
|
||||
>
|
||||
{itemsByCategory[category]?.map((member, index) => (
|
||||
<Link
|
||||
className={`dark:border-dark-100 border-light-800 focus:ring-width-2 focus:ring-blurple ml-5 flex flex-col border-l p-[5px] pl-6 outline-none focus:rounded focus:border-0 focus:ring ${
|
||||
decodeURIComponent(pathname ?? '') === member.href
|
||||
? 'bg-blurple text-white'
|
||||
: 'dark:hover:bg-dark-200 dark:active:bg-dark-100 hover:bg-light-700 active:bg-light-800'
|
||||
}`}
|
||||
href={member.href}
|
||||
key={`${member.title}-${index}`}
|
||||
onClick={() => setOpened(false)}
|
||||
title={member.title}
|
||||
>
|
||||
<div className="flex flex-row place-items-center gap-2 lg:text-sm">
|
||||
<span className="truncate">{member.title}</span>
|
||||
</div>
|
||||
</Link>
|
||||
))}
|
||||
</Section>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
import { Section } from '@discordjs/ui';
|
||||
import type { MDXInstance } from 'astro';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { useLocation } from 'react-use';
|
||||
|
||||
export type MDXPage = MDXInstance<{ category: string; title: string }>;
|
||||
|
||||
export function SidebarItems({ pages }: { pages: MDXPage[] }) {
|
||||
const state = useLocation();
|
||||
const [active, setActive] = useState<string | undefined>('');
|
||||
|
||||
const categories = useMemo(
|
||||
() =>
|
||||
pages.reduce<Record<string, MDXPage[]>>((acc, page) => {
|
||||
if (acc[page.frontmatter.category]) {
|
||||
acc[page.frontmatter.category]?.push(page);
|
||||
} else {
|
||||
acc[page.frontmatter.category] = [page];
|
||||
}
|
||||
|
||||
return acc;
|
||||
}, {}),
|
||||
[pages],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
setActive(state.pathname);
|
||||
}, [state]);
|
||||
|
||||
return Object.keys(categories).map((category, idx) => (
|
||||
<Section key={`${category}-${idx}`} title={category}>
|
||||
{categories[category]?.map((member, index) => (
|
||||
<a
|
||||
className={`dark:border-dark-100 border-light-800 focus:ring-width-2 focus:ring-blurple ml-5 flex flex-col border-l p-[5px] pl-6 outline-0 focus:rounded focus:border-0 focus:ring ${
|
||||
(member.url || '/') === active
|
||||
? 'bg-blurple text-white'
|
||||
: 'dark:hover:bg-dark-200 dark:active:bg-dark-100 hover:bg-light-700 active:bg-light-800'
|
||||
}`}
|
||||
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
|
||||
href={member.url || '/'}
|
||||
key={`${member.frontmatter.title}-${index}}`}
|
||||
title={member.frontmatter.title}
|
||||
>
|
||||
<div className="flex flex-row place-items-center gap-2 lg:text-sm">
|
||||
<span className="truncate">{member.frontmatter.title}</span>
|
||||
</div>
|
||||
</a>
|
||||
)) ?? null}
|
||||
</Section>
|
||||
));
|
||||
}
|
||||
20
apps/guide/src/components/ThemeSwitcher.tsx
Normal file
@@ -0,0 +1,20 @@
|
||||
'use client';
|
||||
|
||||
import { VscColorMode } from '@react-icons/all-files/vsc/VscColorMode';
|
||||
import { Button } from 'ariakit/button';
|
||||
import { useTheme } from 'next-themes';
|
||||
|
||||
export default function ThemeSwitcher() {
|
||||
const { resolvedTheme, setTheme } = useTheme();
|
||||
const toggleTheme = () => setTheme(resolvedTheme === 'light' ? 'dark' : 'light');
|
||||
|
||||
return (
|
||||
<Button
|
||||
aria-label="Toggle theme"
|
||||
className="h-6 w-6 flex flex-row transform-gpu cursor-pointer select-none appearance-none place-items-center border-0 rounded rounded-full bg-transparent p-0 text-sm font-semibold leading-none no-underline outline-none active:translate-y-px focus:ring focus:ring-width-2 focus:ring-blurple"
|
||||
onClick={() => toggleTheme()}
|
||||
>
|
||||
<VscColorMode size={24} />
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
@@ -9,14 +9,13 @@ category: Home
|
||||
<DiscordMessage
|
||||
interaction={{
|
||||
author: {
|
||||
avatar:
|
||||
'https://cdn.discordapp.com/guilds/222078108977594368/users/81440962496172032/avatars/c059c5d04d717ea05790f7a6447e4843.webp?size=160',
|
||||
username: 'Crawl',
|
||||
avatar: '/assets/old-guide.png',
|
||||
username: 'discord.js',
|
||||
},
|
||||
command: 'upgrade',
|
||||
command: '/upgrade',
|
||||
}}
|
||||
author={{
|
||||
avatar: 'https://cdn.discordapp.com/avatars/474807795183648809/7f239a0776ff928b2182906a2b3743c9.webp?size=160',
|
||||
avatar: '/assets/discordjs.png',
|
||||
bot: true,
|
||||
username: 'Guide Bot',
|
||||
time: 'Today at 21:00',
|
||||
@@ -30,14 +29,11 @@ category: Home
|
||||
|
||||
## Site
|
||||
|
||||
- Upgraded to [VuePress v2](https://v2.vuepress.vuejs.org/)
|
||||
- New theme made to match the [discord.js documentation site](https://discord.js.org/)
|
||||
- Discord message components upgraded to [@discord-message-components/vue](https://github.com/Danktuary/discord-message-components/blob/main/packages/vue/README.md)
|
||||
- Many fixes in code blocks, grammar, consistency, etc.
|
||||
We have moved from VuePress to [Next.js](https://nextjs.org/)! The source can be found [here](https://github.com/discordjs/discord.js/tree/main/apps/guide).
|
||||
|
||||
## Pages
|
||||
|
||||
All content has been updated to use discord.js v14 syntax. The v13 version of the guide can be found at [https://v13.discordjs.guide/](https://v13.discordjs.guide/).
|
||||
All content has been updated to use discord.js v14 syntax. The v13 version of the guide can be found at https://v13.discordjs.guide.
|
||||
|
||||
### New
|
||||
|
||||
@@ -54,13 +50,13 @@ All content has been updated to use discord.js v14 syntax. The v13 version of th
|
||||
- [Voice](/voice/): Rewritten to use the [_`@discordjs/voice`_](https://github.com/discordjs/discord.js/tree/main/packages/voice) package
|
||||
- [Command handling](/creating-your-bot/command-handling.md/): Updated to use slash commands
|
||||
- Obsolete sections removed
|
||||
- _`client.on('message')`_ snippets updated to _`client.on('interactionCreate')`_
|
||||
- [Message content will become a new privileged intent on August 31, 2022](https://support-dev.discord.com/hc/en-us/articles/4404772028055)
|
||||
- _`client.on('message')`_ snippets updated to _`client.on(Events.InteractionCreate)`_
|
||||
- [Message content became a privileged intent on August 31, 2022](https://support-dev.discord.com/hc/articles/4404772028055)
|
||||
|
||||
<DiscordMessages rounded>
|
||||
<DiscordMessage
|
||||
author={{
|
||||
avatar: 'https://cdn.discordapp.com/avatars/474807795183648809/7f239a0776ff928b2182906a2b3743c9.webp?size=160',
|
||||
avatar: '/assets/discordjs.png',
|
||||
bot: true,
|
||||
username: 'Guide Bot',
|
||||
time: 'Today at 21:00',
|
||||
198
apps/guide/src/content/01-home/03-how-to-contribute.mdx
Normal file
@@ -0,0 +1,198 @@
|
||||
---
|
||||
title: How to contribute
|
||||
category: Home
|
||||
---
|
||||
|
||||
# How to contribute
|
||||
|
||||
Since this guide is made specifically for the discord.js community, we want to be sure to provide the most relevant and up-to-date content. We will, of course, make additions to the current pages and add new ones as we see fit, but fulfilling requests is how we know we're providing content you all want the most.
|
||||
|
||||
Requests may be as simple as "add an example to the [frequently asked questions](/popular-topics/faq.html) page", or as elaborate as "add a page regarding [sharding](/sharding/)". We'll do our best to fulfill all requests, as long as they're reasonable.
|
||||
|
||||
To make a request, simply head over to [the repository's issue tracker](https://github.com/discordjs/discord.js/issues) and [create a new issue](https://github.com/discordjs/discord.js/issues/new)! Title it appropriately, and let us know exactly what you mean inside the issue description. Make sure that you've looked around the site before making a request; what you want to request might already exist!
|
||||
|
||||
<Alert title="Tip" type="success">
|
||||
Remember that you can always [fork the repository](https://github.com/discordjs/discord.js/fork) and [make a pull
|
||||
request](https://github.com/discordjs/discord.js/pulls) if you want to add anything to the guide yourself!
|
||||
</Alert>
|
||||
|
||||
We'll also get into some of the more advanced features this guide does below.
|
||||
|
||||
## Components
|
||||
|
||||
Throughout the guide, you'll see some components from the _`@discordjs/ui`_ package:
|
||||
|
||||
- _`Alert`_
|
||||
- _`Section`_
|
||||
- _`DiscordMessages`_, _`DiscordMessage`_, and _`DiscordMessageEmbed`_
|
||||
|
||||
Check the source of this page to see them in action!
|
||||
|
||||
### Alert
|
||||
|
||||
This component may take a _`title`_ and a _`type`_ of _`'danger' | 'info' | 'success' | 'warning'`_.
|
||||
|
||||
This uses _`title="Alert" type="info"`_:
|
||||
|
||||
<Alert title="Alert" type="info">
|
||||
Use these appropriately!
|
||||
</Alert>
|
||||
|
||||
### Section
|
||||
|
||||
<Section title="Expand me!" padding defaultClosed background gutter>
|
||||
Well, hello there!
|
||||
|
||||
Whenever some text does not need to be in the main body, you can put it here.
|
||||
|
||||
- _`title`_: The title that'll appear.
|
||||
- _`padding`_: Adds padding.
|
||||
- _`dense`_: When _`padding`_ is specified, _`dense`_ could make it appear, well, dense.
|
||||
- _`defaultClosed`_ Whether the section is closed by default. This one was.
|
||||
- _`background`_ Adds background to the content.
|
||||
- _`gutter`_: This adds a very small appealing space between the expansion of the section and its content.
|
||||
|
||||
</Section>
|
||||
|
||||
### DiscordMessages, DiscordMessage, and DiscordMessageEmbed
|
||||
|
||||
<DiscordMessages>
|
||||
<DiscordMessage
|
||||
author={{
|
||||
avatar: '/assets/discordjs.png',
|
||||
bot: true,
|
||||
time: 'Today at 21:00',
|
||||
username: 'Guide Bot',
|
||||
}}
|
||||
>
|
||||
A _`DiscordMessage`_ must be within _`DiscordMessages`_.
|
||||
</DiscordMessage>
|
||||
<DiscordMessage
|
||||
author={{
|
||||
avatar: '/assets/discordjs.png',
|
||||
bot: true,
|
||||
time: 'Today at 21:01',
|
||||
username: 'Guide Bot',
|
||||
}}
|
||||
reply={{
|
||||
author: {
|
||||
avatar: '/assets/discordjs.png',
|
||||
bot: true,
|
||||
username: 'Guide Bot',
|
||||
},
|
||||
content: 'A _`DiscordMessage`_ must be within _`DiscordMessages`_.',
|
||||
}}
|
||||
time="21:02"
|
||||
>
|
||||
It's much better to see the source code of this page to replicate and learn!
|
||||
</DiscordMessage>
|
||||
<DiscordMessage
|
||||
author={{
|
||||
avatar: '/assets/discordjs.png',
|
||||
bot: true,
|
||||
time: 'Today at 21:02',
|
||||
username: 'Guide Bot',
|
||||
}}
|
||||
>
|
||||
This message depicts the use of embeds.
|
||||
<>
|
||||
<DiscordMessageEmbed
|
||||
author={{
|
||||
avatar: '/assets/discordjs.png',
|
||||
username: 'Guide Bot',
|
||||
}}
|
||||
footer={{ content: 'Sometimes, titles just have to be.' }}
|
||||
title={{ title: 'An amazing title' }}
|
||||
>
|
||||
This is a description. You can put a description here. It must be descriptive!
|
||||
</DiscordMessageEmbed>
|
||||
<DiscordMessageEmbed
|
||||
author={{
|
||||
avatar: '/assets/discordjs.png',
|
||||
username: 'Guide Bot',
|
||||
}}
|
||||
footer={{ content: "When one amazing title just wasn't enough." }}
|
||||
title={{ title: 'Another amazing title' }}
|
||||
>
|
||||
Multiple embeds!
|
||||
</DiscordMessageEmbed>
|
||||
</>
|
||||
</DiscordMessage>
|
||||
<DiscordMessage
|
||||
author={{
|
||||
avatar: '/assets/discordjs.png',
|
||||
bot: true,
|
||||
time: 'Today at 21:03',
|
||||
username: 'Guide Bot',
|
||||
}}
|
||||
interaction={{
|
||||
author: {
|
||||
avatar: '/assets/discordjs.png',
|
||||
bot: true,
|
||||
username: 'Guide Bot',
|
||||
},
|
||||
command: '/interaction',
|
||||
}}
|
||||
>
|
||||
Interactions are supported! I definitely used a command.
|
||||
</DiscordMessage>
|
||||
<DiscordMessage
|
||||
author={{
|
||||
avatar: '/assets/discordjs.png',
|
||||
bot: true,
|
||||
color: 'text-red-500',
|
||||
time: 'Today at 21:04',
|
||||
username: 'Guide Bot',
|
||||
}}
|
||||
reply={{
|
||||
author: {
|
||||
avatar: '/assets/snek-bot.jpeg',
|
||||
bot: true,
|
||||
verified: true,
|
||||
color: 'text-blue-500',
|
||||
username: 'Snek Bot',
|
||||
},
|
||||
content: 'You can also have verified bots, like me!',
|
||||
}}
|
||||
>
|
||||
Display colors are supported as well!
|
||||
</DiscordMessage>
|
||||
</DiscordMessages>
|
||||
|
||||
## Code blocks
|
||||
|
||||
We use [Code Hike](https://codehike.org). Here are some example code blocks, which should be easy to grasp and learn upon reading the source code of this page:
|
||||
|
||||
<CH.Code>
|
||||
|
||||
```ts
|
||||
const HELLO = 'hello' as const;
|
||||
console.log(HELLO);
|
||||
// "ts" is the language of the code block.
|
||||
```
|
||||
|
||||
</CH.Code>
|
||||
|
||||
<CH.Code>
|
||||
|
||||
```ts fileName
|
||||
const FILE_NAME = 'fileName' as const;
|
||||
if (FILE_NAME.includes(' ')) throw new Error('Spaces cannot be used in file names.');
|
||||
```
|
||||
|
||||
```ts anotherFileName
|
||||
const FILE_NAME_2 = 'anotherFileName' as const;
|
||||
// Putting code blocks together makes them appear in tabs, just like in your editor.
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
```ts requiredName
|
||||
const FILE_NAME_3 = 'requiredName' as const;
|
||||
if (!FILE_NAME) throw new Error('There must be a file name to use panels!');
|
||||
// The --- divider was used to create a panel.
|
||||
```
|
||||
|
||||
</CH.Code>
|
||||
|
||||
For more information, be sure to check out the [documentation](https://codehike.org/docs/ch-code).
|
||||
@@ -0,0 +1,102 @@
|
||||
---
|
||||
title: Installing Node.js and discord.js
|
||||
category: Installations and preparations
|
||||
---
|
||||
|
||||
# Installing Node.js and discord.js
|
||||
|
||||
## Installing Node.js
|
||||
|
||||
To use discord.js, you'll need to install [Node.js](https://nodejs.org/). discord.js v14 requires Node v16.9.0 or higher.
|
||||
|
||||
<Alert title="Tip" type="success">
|
||||
To check if you already have Node installed on your machine \(e.g., if you're using a VPS\), run _`node -v`_ in your
|
||||
terminal. If it outputs _`v16.9.0`_ or higher, then you're good to go! Otherwise, continue reading.
|
||||
</Alert>
|
||||
|
||||
On Windows, it's as simple as installing any other program. Download the latest version from [the Node.js website](https://nodejs.org/), open the downloaded file, and follow the steps from the installer.
|
||||
|
||||
On macOS, either:
|
||||
|
||||
- Download the latest version from [the Node.js website](https://nodejs.org/), open the package installer, and follow the instructions
|
||||
- Use a package manager like [Homebrew](https://brew.sh/) with the command _`brew install node`_
|
||||
|
||||
On Linux, you can consult [this page](https://nodejs.org/en/download/package-manager/) to determine how you should install Node. Native package managers often default to outdated versions of Node, so make sure you follow the recommended approach for your chosen Linux distribution carefully.
|
||||
|
||||
## Preparing the essentials
|
||||
|
||||
To use discord.js, you'll need to install it via npm \(Node's package manager\). npm comes with every Node installation, so you don't have to worry about installing that. However, before you install anything, you should set up a new project folder.
|
||||
|
||||
Navigate to a suitable place on your machine and create a new folder named _`discord-bot`_ (or whatever you want). Next you'll need to open your terminal.
|
||||
|
||||
### Opening the terminal
|
||||
|
||||
<Alert title="Tip" type="success">
|
||||
If you use [Visual Studio Code](https://code.visualstudio.com/), you can press <kbd>Ctrl + `</kbd> (backtick) to open
|
||||
its integrated terminal.
|
||||
</Alert>
|
||||
|
||||
On Windows, either:
|
||||
|
||||
- <kbd>Shift + Right-click</kbd> inside your project directory and choose the "Open command window here" option
|
||||
- Press <kbd>Win + R</kbd> and run _`cmd.exe`_, and then _`cd`_ into your project directory
|
||||
|
||||
On macOS, either:
|
||||
|
||||
- Open Launchpad or Spotlight and search for "Terminal"
|
||||
- In your "Applications" folder, under "Utilities", open the Terminal app
|
||||
|
||||
On Linux, you can quickly open the terminal with <kbd>Ctrl + Alt + T</kbd>.
|
||||
|
||||
With the terminal open, run the _`node -v`_ command to make sure you've successfully installed Node.js. If it outputs _`v16.9.0`_ or higher, great!
|
||||
|
||||
### Initiating a project folder
|
||||
|
||||
<CH.Code lineNumbers={false}>
|
||||
|
||||
```sh npm
|
||||
npm init; npm pkg set type="module"
|
||||
```
|
||||
|
||||
```sh yarn
|
||||
yarn init
|
||||
# You must go into your package.json file and add "type": "module"
|
||||
```
|
||||
|
||||
```sh pnpm
|
||||
pnpm init; pnpm pkg set type="module"
|
||||
```
|
||||
|
||||
</CH.Code>
|
||||
|
||||
This is the next command you'll be running. This command creates a _`package.json`_ file for you, which will keep track of the dependencies your project uses, as well as other info.
|
||||
|
||||
This command will ask you a sequence of questions–you should fill them out as you see fit. If you're not sure of something or want to skip it as a whole, leave it blank and press enter. Setting the package type as _`module`_ tells Node that you'll be writing this project using ESM \(ECMAScript modules\), supporting the latest JavaScript syntax and features.
|
||||
|
||||
Once you're done with that, you're ready to install discord.js!
|
||||
|
||||
## Installing discord.js
|
||||
|
||||
Now that you've installed Node.js and know how to open your console and run commands, you can finally install discord.js! Run the following command in your terminal:
|
||||
|
||||
<CH.Code lineNumbers={false}>
|
||||
|
||||
```sh npm
|
||||
npm install discord.js
|
||||
```
|
||||
|
||||
```sh yarn
|
||||
yarn add discord.js
|
||||
```
|
||||
|
||||
```sh pnpm
|
||||
pnpm add discord.js
|
||||
```
|
||||
|
||||
</CH.Code>
|
||||
|
||||
And that's it! With all the necessities installed, you're almost ready to start coding your bot.
|
||||
|
||||
## Installing a linter
|
||||
|
||||
While you are coding, it's possible to run into numerous syntax errors or code in an inconsistent style. You should [install a linter](./setting-up-a-linter) to ease these troubles. While code editors generally can point out syntax errors, linters coerce your code into a specific style as defined by the configuration. While this is not required, it is advised.
|
||||
@@ -0,0 +1,6 @@
|
||||
---
|
||||
title: Setting up a linter
|
||||
category: Installations and preparations
|
||||
---
|
||||
|
||||
TODO: Rewrite. Placeholder page for ordering.
|
||||
@@ -0,0 +1,61 @@
|
||||
---
|
||||
title: Setting up a bot application
|
||||
category: Installations and preparations
|
||||
---
|
||||
|
||||
# Setting up a bot application
|
||||
|
||||
## Creating your bot
|
||||
|
||||
Now that you've installed Node, discord.js, and hopefully a linter, you're almost ready to start coding! The next step you need to take is setting up an actual Discord bot application via Discord's website.
|
||||
|
||||
It's effortless to create one. The steps you need to take are as follows:
|
||||
|
||||
1. Open the [Discord developer portal](https://discord.com/developers/applications) and log into your account.
|
||||
2. Click on the "New Application" button.
|
||||
3. Enter a name and confirm the pop-up window by clicking the "Create" button.
|
||||
|
||||
You should see a page like this:
|
||||
|
||||

|
||||
|
||||
You can edit your application's name, description, and avatar here. Once you've saved your changes, move on by selecting the "Bot" tab in the left pane.
|
||||
|
||||
## Your bot's token
|
||||
|
||||
<Alert title="Important" type="danger">
|
||||
This section is critical, so pay close attention. It explains what your bot token is, as well as the security aspects
|
||||
of it.
|
||||
</Alert>
|
||||
|
||||
On the bot tab, you'll see a section like this:
|
||||
|
||||

|
||||
|
||||
In this panel, you can give your bot a snazzy avatar, set its username, and make it public or private. Your bot's token will be revealed when you press the "Reset Token" button and confirm. When we ask you to paste your bot's token somewhere, this is the value that you need to put in. If you happen to lose your bot's token at some point, you need to come back to this page and reset your bot's token again which will reveal the new token, invalidating all old ones.
|
||||
|
||||
### What is a token, anyway?
|
||||
|
||||
A token is essentially your bot's password; it's what your bot uses to login to Discord. With that said, **it is vital that you do not ever share this token with anybody, purposely or accidentally**. If someone does manage to get a hold of your bot's token, they can use your bot as if it were theirs—this means they can perform malicious acts with it.
|
||||
|
||||
Tokens look like this: _`NzkyNzE1NDU0MTk2MDg4ODQy.X-hvzA.Ovy4MCQywSkoMRRclStW4xAYK7I`_ (don't worry, we immediately reset this token before even posting it here!). If it's any shorter and looks more like this: _`kxbsDRU5UfAaiO7ar9GFMHSlmTwYaIYn`_, you copied your client secret instead. Make sure to copy the token if you want your bot to work!
|
||||
|
||||
### Token leak scenario
|
||||
|
||||
Let's imagine that you have a bot on over 1,000 servers, and it took you many, many months of coding and patience to get it on that amount. Your bot's token gets leaked somewhere, and now someone else has it. That person can:
|
||||
|
||||
- Spam every server your bot is on;
|
||||
- DM spam as many users as possible;
|
||||
- Delete as many channels as possible;
|
||||
- Kick or ban as many server members as possible;
|
||||
- Make your bot leave all of the servers it has joined;
|
||||
|
||||
All that and much, much more. Sounds pretty terrible, right? So make sure to keep your bot's token as safe as possible!
|
||||
|
||||
In the [configuration files](../creating-your-bot/configuration-files) page of the guide, we cover how to safely store your bot's token in a configuration file.
|
||||
|
||||
<Alert title="Compromised tokens" type="danger">
|
||||
If your bot token has been compromised by committing it to a public repository, posting it in discord.js support etc.
|
||||
or otherwise see your bot's token in danger, return to this page and press "Reset Token". This will invalidate all old
|
||||
tokens belonging to your bot. Keep in mind that you will need to update your bot's token where you used it before.
|
||||
</Alert>
|
||||
@@ -0,0 +1,52 @@
|
||||
---
|
||||
title: Adding your bot to servers
|
||||
category: Installations and preparations
|
||||
---
|
||||
|
||||
# Adding your bot to servers
|
||||
|
||||
After you [set up a bot application](./setting-up-a-bot-application), you'll notice that it's not in any servers yet. So how does that work?
|
||||
|
||||
Before you're able to see your bot in your own (or other) servers, you'll need to add it by creating and using a unique invite link using your bot application's client id.
|
||||
|
||||
## Bot invite links
|
||||
|
||||
The basic version of one such link looks like this:
|
||||
|
||||
<CH.Code lineNumbers={false}>
|
||||
|
||||
```
|
||||
https://discord.com/api/oauth2/authorize?client_id=123456789012345678&permissions=0&scope=bot%20applications.commands
|
||||
```
|
||||
|
||||
</CH.Code>
|
||||
|
||||
The structure of the URL is quite simple:
|
||||
|
||||
- _`https://discord.com/api/oauth2/authorize`_ is Discord's standard structure for authorizing an OAuth2 application (such as your bot application) for entry to a Discord server.
|
||||
- _`client_id=...`_ is to specify _which_ application you want to authorize. You'll need to replace this part with your client's id to create a valid invite link.
|
||||
- _`permissions=...`_ describes the permissions that your bot will request to be granted by default upon joining the server you are adding it to.
|
||||
- _`scope=bot%20applications.commands`_ specifies that you want to add this application as a Discord bot, with the ability to create slash commands.
|
||||
|
||||
<Alert title="Warning" type="warning">
|
||||
If you get an error message saying "Bot requires a code grant", head over to your application's settings and disable
|
||||
the "Require OAuth2 Code Grant" option. You shouldn't enable this option unless you know why you need to.
|
||||
</Alert>
|
||||
|
||||
## Creating and using your invite link
|
||||
|
||||
To create an invite link, head back to the [My Apps](https://discord.com/developers/applications/me) page under the "Applications" section, click on your bot application, and open the OAuth2 page.
|
||||
|
||||
In the sidebar, you'll find the OAuth2 URL generator. Select the _`bot`_ and _`applications.commands`_ options. Once you select the _`bot`_ option, a list of permissions will appear, allowing you to configure the permissions your bot needs.
|
||||
|
||||
Grab the link via the "Copy" button and enter it in your browser. You should see something like this (with your bot's username and avatar):
|
||||
|
||||

|
||||
|
||||
Choose the server you want to add it to and click "Authorize". Do note that you'll need the "Manage Server" permission on a server to add your bot there. This should then present you a nice confirmation message:
|
||||
|
||||

|
||||
|
||||
Congratulations! You've successfully added your bot to your Discord server. It should show up in your server's member list somewhat like this:
|
||||
|
||||

|
||||
@@ -0,0 +1,132 @@
|
||||
---
|
||||
title: Configuration files
|
||||
category: Creating your bot
|
||||
---
|
||||
|
||||
# Configuration files
|
||||
|
||||
Once you [add your bot to a server](../installations-and-preparations/adding-your-bot-to-servers), the next step is to start coding and get it online! Let's start by creating a config file to prepare the necessary values your client will need.
|
||||
|
||||
As explained in the ["What is a token, anyway?"](../installations-and-preparations/setting-up-a-bot-application.md#what-is-a-token-anyway) section, your token is essentially your bot's password, and you should protect it as best as possible. This can be done through a _`config.json`_ file or by using environment variables.
|
||||
|
||||
Open your application in the [Discord Developer Portal](https://discord.com/developers/applications) and go to the "Bot" page to copy your token.
|
||||
|
||||
## Using config.json
|
||||
|
||||
Storing data in a _`config.json`_ file is a common way of keeping your sensitive values safe. Create a _`config.json`_ file in your project directory and paste in your token. You can access your token inside other files by importing this file.
|
||||
|
||||
<CH.Code lineNumbers={false}>
|
||||
|
||||
```json config.json
|
||||
{
|
||||
"token": "your-token-goes-here"
|
||||
}
|
||||
```
|
||||
|
||||
```js index.js
|
||||
import config from './config.json' assert { type: 'json' };
|
||||
|
||||
console.log(config.token);
|
||||
```
|
||||
|
||||
</CH.Code>
|
||||
|
||||
<Alert title="Danger" type="danger">
|
||||
If you're using Git, you should not commit this file and should [ignore it via `.gitignore`](#git-and-gitignore).
|
||||
</Alert>
|
||||
|
||||
## Using environment variables
|
||||
|
||||
Environment variables are special values for your environment (e.g., terminal session, Docker container, or environment variable file). You can pass these values into your code's scope so that you can use them.
|
||||
|
||||
One way to pass in environment variables is via the command line interface. When starting your app, instead of _`node index.js`_, use _`TOKEN=your-token-goes-here node index.js`_. You can repeat this pattern to expose other values as well.
|
||||
|
||||
You can access the set values in your code via the _`process.env`_ global variable, accessible in any file. Note that values passed this way will always be strings and that you might need to parse them to a number, if using them to do calculations.
|
||||
|
||||
<CH.Code lineNumbers={false} rows={3}>
|
||||
|
||||
```sh Shell
|
||||
A=123 B=456 DISCORD_TOKEN=your-token-goes-here node index.js
|
||||
```
|
||||
|
||||
```js index.js
|
||||
console.log(process.env.A);
|
||||
console.log(process.env.B);
|
||||
console.log(process.env.DISCORD_TOKEN);
|
||||
```
|
||||
|
||||
</CH.Code>
|
||||
|
||||
### Using dotenv
|
||||
|
||||
Another common approach is storing these values in a _`.env`_ file. This spares you from always copying your token into the command line. Each line in a _`.env`_ file should hold a _`KEY=value`_ pair.
|
||||
|
||||
You can use the [`dotenv` package](https://www.npmjs.com/package/dotenv) for this. Once installed, require and use the package to load your _`.env`_ file and attach the variables to _`process.env`_:
|
||||
|
||||
<CH.Code lineNumbers={false}>
|
||||
|
||||
```sh npm
|
||||
npm install dotenv
|
||||
```
|
||||
|
||||
```sh yarn
|
||||
yarn add dotenv
|
||||
```
|
||||
|
||||
```sh pnpm
|
||||
pnpm add dotenv
|
||||
```
|
||||
|
||||
</CH.Code>
|
||||
|
||||
<CH.Code lineNumbers={false} rows={7}>
|
||||
|
||||
```sh .env
|
||||
A=123
|
||||
B=456
|
||||
DISCORD_TOKEN=your-token-goes-here
|
||||
```
|
||||
|
||||
```js index.js
|
||||
import { config } from 'dotenv';
|
||||
|
||||
config();
|
||||
|
||||
console.log(process.env.A);
|
||||
console.log(process.env.B);
|
||||
console.log(process.env.DISCORD_TOKEN);
|
||||
```
|
||||
|
||||
</CH.Code>
|
||||
|
||||
<Alert title="Danger" type="danger">
|
||||
If you're using Git, you should not commit this file and should [ignore it via `.gitignore`](#git-and-gitignore).
|
||||
</Alert>
|
||||
|
||||
<Alert title="Online editors (Glitch, Heroku, Replit, etc.)" type="info">
|
||||
While we generally do not recommend using online editors as hosting solutions, but rather invest in a proper virtual private server, these services do offer ways to keep your credentials safe as well! Please see the respective service's documentation and help articles for more information on how to keep sensitive values safe:
|
||||
|
||||
- Glitch: [Storing secrets in .env](https://glitch.happyfox.com/kb/article/18)
|
||||
- Heroku: [Configuration variables](https://devcenter.heroku.com/articles/config-vars)
|
||||
- Replit: [Secrets and environment variables](https://docs.replit.com/repls/secrets-environment-variables)
|
||||
|
||||
</Alert>
|
||||
|
||||
## Git and .gitignore
|
||||
|
||||
Git is a fantastic tool to keep track of your code changes and allows you to upload progress to services like [GitHub](https://github.com/), [GitLab](https://about.gitlab.com/), or [Bitbucket](https://bitbucket.org/product). While this is super useful to share code with other developers, it also bears the risk of uploading your configuration files with sensitive values!
|
||||
|
||||
You can specify files that Git should ignore in its versioning systems with a*`.gitignore`* file. Create a _`.gitignore`_ file in your project directory and add the names of the files and folders you want to ignore:
|
||||
|
||||
```
|
||||
node_modules
|
||||
.env
|
||||
config.json
|
||||
```
|
||||
|
||||
<Alert title="Tip" type="success">
|
||||
Aside from keeping credentials safe, _`node_modules`_ should be included here. Since this directory can be restored based on the entries in your _`package.json`_ and _`package-lock.json`_ files by running _`npm install`_, it does not need to be included in Git.
|
||||
|
||||
You can specify quite intricate patterns in _`.gitignore`_ files, check out the [Git documentation on `.gitignore`](https://git-scm.com/docs/gitignore) for more information!
|
||||
|
||||
</Alert>
|
||||
@@ -0,0 +1,60 @@
|
||||
---
|
||||
title: Creating the main file
|
||||
category: Creating your bot
|
||||
---
|
||||
|
||||
# Creating the main file
|
||||
|
||||
<Alert title="Tip" type="success">
|
||||
This page assumes you've already prepared the [configuration files](./configuration-files) from the previous page.
|
||||
We're using the _`config.json`_ approach, however feel free to substitute your own!
|
||||
</Alert>
|
||||
|
||||
Open your code editor and create a new file. We suggest that you save the file as _`index.js`_, but you may name it whatever you wish.
|
||||
|
||||
Here's the base code to get you started:
|
||||
|
||||
<CH.Code>
|
||||
|
||||
```js
|
||||
// Require the necessary discord.js classes
|
||||
import { Client, Events, GatewayIntentBits } from 'discord.js';
|
||||
import config from './config.json' assert { type: 'json' };
|
||||
|
||||
// Create a new client instance
|
||||
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
|
||||
|
||||
// When the client is ready, run this code (only once)
|
||||
// We use 'c' for the event parameter to keep it separate from the already defined 'client'
|
||||
client.once(Events.ClientReady, (c) => {
|
||||
console.log(`Ready! Logged in as ${c.user.tag}`);
|
||||
});
|
||||
|
||||
// Log in to Discord with your client's token
|
||||
client.login(config.token);
|
||||
```
|
||||
|
||||
</CH.Code>
|
||||
|
||||
This is how you create a client instance for your Discord bot and log in to Discord. The _`GatewayIntentBits.Guilds`_ intents option is necessary for the discord.js client to work as you expect it to, as it ensures that the caches for guilds, channels, and roles are populated and available for internal use.
|
||||
|
||||
<Alert title="Tip" type="success">
|
||||
The term "guild" is used by the Discord API and in discord.js to refer to a Discord server.
|
||||
</Alert>
|
||||
|
||||
Intents also define which events Discord should send to your bot, and you may wish to enable more than just the minimum. You can read more about the other intents on the [Intents topic](../popular-topics/intents).
|
||||
|
||||
## Running your application
|
||||
|
||||
Open your terminal and run _`node index.js`_ to start the process. If you see "Ready!" after a few seconds, you're good to go! The next step is to start adding [slash commands](./adding-commands) to develop your bot's functionality.
|
||||
|
||||
<Alert title="Tip" type="success">
|
||||
You can open your _`package.json`_ file and edit the _`"main": "index.js"`_ field to point to your main file. You can then run _`node .`_ in your terminal to start the process!
|
||||
|
||||
After closing the process with _`Ctrl + C`_, you can press the up arrow on your keyboard to bring up the latest commands you've run. Pressing up and then enter after closing the process is a quick way to start it up again.
|
||||
|
||||
</Alert>
|
||||
|
||||
#### Resulting code
|
||||
|
||||
<ResultingCode path="creating-your-bot/initial-files" />
|
||||
@@ -0,0 +1,163 @@
|
||||
---
|
||||
title: Adding commands
|
||||
category: Creating your bot
|
||||
---
|
||||
|
||||
# Creating slash commands
|
||||
|
||||
Discord allows developers to register [slash commands](https://discord.com/developers/docs/interactions/application-commands), which provide users a first-class way of interacting directly with your application.
|
||||
|
||||
Slash commands provide a huge number of benefits over manual message parsing, including:
|
||||
|
||||
- Integration with the Discord client interface.
|
||||
- Automatic command detection and parsing of the associated options/arguments.
|
||||
- Typed argument inputs for command options, e.g. "String", "User", or "Role".
|
||||
- Validated or dynamic choices for command options.
|
||||
- In-channel private responses (ephemeral messages).
|
||||
- Pop-up form-style inputs for capturing additional information.
|
||||
|
||||
...and many more!
|
||||
|
||||
<Alert title="Read first!" type="info">
|
||||
For fully functional slash commands, there are three important pieces of code that need to be written. They are:
|
||||
|
||||
1. The individual command files, containing their definitions and functionality.
|
||||
2. The [command handler](command-handling.html), which dynamically reads the files and executes the commands.
|
||||
3. The [command deployment script](command-deployment.html), to register your slash commands with Discord so they appear in the interface.
|
||||
|
||||
These steps can be done in any order, but **all are required** before the commands are fully functional.
|
||||
|
||||
On this page, you'll complete Step 1. Make sure to also complete the other pages linked above!
|
||||
|
||||
</Alert>
|
||||
|
||||
## Before you continue
|
||||
|
||||
Assuming you've followed the guide so far, your project directory should look something like this:
|
||||
|
||||
```:no-line-numbers
|
||||
discord-bot/
|
||||
├── node_modules
|
||||
├── config.json
|
||||
├── index.js
|
||||
├── package-lock.json
|
||||
└── package.json
|
||||
```
|
||||
|
||||
## Individual command files
|
||||
|
||||
Create a new folder named _`commands`_, which is where you'll store all of your command files.
|
||||
|
||||
At a minimum, the definition of a slash command must have a name and a description. Slash command names must be between 1-32 characters and contain no capital letters, spaces, or symbols other than _`-`_ and _`_`_. Using the builder, a simple _`ping`\_ command definition would look like this:
|
||||
|
||||
<CH.Code>
|
||||
|
||||
```js
|
||||
/** @type {import('discord.js').RESTPostAPIApplicationCommandsJSONBody} */
|
||||
export const data = {
|
||||
name: 'ping',
|
||||
description: 'Replies with Pong!',
|
||||
};
|
||||
```
|
||||
|
||||
</CH.Code>
|
||||
|
||||
A slash command also requires a function to run when the command is used, to respond to the interaction. Using an interaction response method confirms to Discord that your bot successfully received the interaction, and has responded to the user. Discord enforces this to ensure that all slash commands provide a good user experience (UX). Failing to respond will cause Discord to show that the command failed, even if your bot is performing other actions as a result.
|
||||
|
||||
The simplest way to acknowledge and respond to an interaction is the _`interaction.reply()`_ method. Other methods of replying are covered on the [Response methods](../slash-commands/response-methods) page later in this section.
|
||||
|
||||
<CH.Code>
|
||||
|
||||
```js
|
||||
/** @param {import('discord.js').CommandInteraction} interaction */
|
||||
export async function execute(interaction) {
|
||||
await interaction.reply('Pong!');
|
||||
}
|
||||
```
|
||||
|
||||
</CH.Code>
|
||||
|
||||
<Alert title="@type and @param tags" type="info">
|
||||
[`@type`](https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#type) and
|
||||
[`@param`](https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#param-and-returns) tags allow you
|
||||
to annotate your code with type information. The tags are not required for your code to run but provide autocomplete
|
||||
and type information for fields and parameters, which can majorly improve your developer experience when working with
|
||||
them.
|
||||
</Alert>
|
||||
|
||||
Put these two together by creating a `commands/ping.js` file for your first command. Inside this file, you're going to define and export two items.
|
||||
|
||||
- The `data` property, which will provide the command definition shown above for registering to Discord.
|
||||
- The `execute` method, which will contain the functionality to run from our event handler when the command is used.
|
||||
|
||||
The _`export`_ keyword ensures these values can be imported and read by other files; namely the command loader and command deployment scripts mentioned earlier.
|
||||
|
||||
<CH.Code>
|
||||
|
||||
```js commands/ping.js
|
||||
/** @type {import('discord.js').RESTPostAPIApplicationCommandsJSONBody} */
|
||||
export const data = {
|
||||
name: 'ping',
|
||||
description: 'Replies with Pong!',
|
||||
};
|
||||
|
||||
/** @param {import('discord.js').CommandInteraction} interaction */
|
||||
export async function execute(interaction) {
|
||||
await interaction.reply('Pong!');
|
||||
}
|
||||
```
|
||||
|
||||
</CH.Code>
|
||||
|
||||
<Alert title="Tip" type="success">
|
||||
[`module.exports`](https://nodejs.org/api/modules.html#modules_module_exports) is how you export data in Node.js so that you can [`require()`](https://nodejs.org/api/modules.html#modules_require_id) it in other files.
|
||||
|
||||
If you need to access your client instance from inside a command file, you can access it via `interaction.client`. If you need to access external files, packages, etc., you should `require()` them at the top of the file.
|
||||
|
||||
</Alert>
|
||||
|
||||
That's it for your basic ping command. Below are examples of two more commands we're going to build upon throughout the guide, so create two more files for these before you continue reading.
|
||||
|
||||
<CH.Code>
|
||||
|
||||
```js commands/user.js
|
||||
/** @type {import('discord.js').RESTPostAPIApplicationCommandsJSONBody} */
|
||||
export const data = {
|
||||
name: 'user',
|
||||
description: 'Provides information about the user.',
|
||||
};
|
||||
|
||||
/** @param {import('discord.js').CommandInteraction} interaction */
|
||||
export async function execute(interaction) {
|
||||
// interaction.user is the object representing the User who ran the command
|
||||
// interaction.member is the GuildMember object, which represents the user in the specific guild
|
||||
await interaction.reply(
|
||||
`This command was run by ${interaction.user.username}, who joined on ${interaction.member.joinedAt}.`,
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
```js commands/server.js
|
||||
/** @type {import('discord.js').RESTPostAPIApplicationCommandsJSONBody} */
|
||||
export const data = {
|
||||
name: 'server',
|
||||
description: 'Provides information about the server.',
|
||||
};
|
||||
|
||||
/** @param {import('discord.js').CommandInteraction} interaction */
|
||||
export async function execute(interaction) {
|
||||
// interaction.guild is the object representing the Guild in which the command was run
|
||||
await interaction.reply(`This server is ${interaction.guild.name} and has
|
||||
${interaction.guild.memberCount} members.`);
|
||||
}
|
||||
```
|
||||
|
||||
</CH.Code>
|
||||
|
||||
#### Next steps
|
||||
|
||||
You can implement additional commands by creating additional files in the _`commands`_ folder, but these three are the ones we're going to use for the examples as we go on. For now let's move on to the code you'll need for command handling, to load the files and respond to incoming interactions.
|
||||
|
||||
#### Resulting code
|
||||
|
||||
<ResultingCode />
|
||||
@@ -0,0 +1,297 @@
|
||||
---
|
||||
title: Handling command interactions
|
||||
category: Creating your bot
|
||||
---
|
||||
|
||||
# Command handling
|
||||
|
||||
Unless your bot project is small, it's not a very good idea to have a single file with a giant _`if`_/_`else if`_ chain for commands. If you want to implement features into your bot and make your development process a lot less painful, you'll want to implement a command handler. Let's get started on that!
|
||||
|
||||
<Alert title="Read first!" type="info">
|
||||
For fully functional slash commands, there are three important pieces of code that need to be written. They are:
|
||||
|
||||
1. The [individual command files](slash-commands), containing their definitions and functionality.
|
||||
2. The command handler, which dynamically reads the files and executes the commands.
|
||||
3. The [command deployment script](command-deployment), to register your slash commands with Discord so they appear in the interface.
|
||||
|
||||
These steps can be done in any order, but **all are required** before the commands are fully functional.
|
||||
|
||||
This page details how to complete **Step 2**. Make sure to also complete the other pages linked above!
|
||||
|
||||
</Alert>
|
||||
|
||||
## Loading command files
|
||||
|
||||
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:
|
||||
|
||||
<CH.Code>
|
||||
|
||||
```js JavaScript mark=1:4,9
|
||||
import { readdir } from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { Client, Collection, Events, GatewayIntentBits } from 'discord.js';
|
||||
import config from './config.json' assert { type: 'json' };
|
||||
|
||||
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
|
||||
|
||||
const commands = new Collection();
|
||||
|
||||
client.once(Events.ClientReady, () => {
|
||||
console.log('Ready!');
|
||||
});
|
||||
```
|
||||
|
||||
```ts TypeScript mark=1:11,16:21
|
||||
import { readdir } from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import {
|
||||
Client,
|
||||
Collection,
|
||||
Events,
|
||||
GatewayIntentBits,
|
||||
type RESTPostAPIChatInputApplicationCommandsJSONBody,
|
||||
type ChatInputCommandInteraction,
|
||||
} from 'discord.js';
|
||||
import config from './config.json';
|
||||
|
||||
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
|
||||
|
||||
interface CommandModule {
|
||||
data: RESTPostAPIChatInputApplicationCommandsJSONBody;
|
||||
execute(interaction: ChatInputCommandInteraction): Promise<void>;
|
||||
}
|
||||
|
||||
const commands = new Collection<string, CommandModule>();
|
||||
|
||||
client.once(Events.ClientReady, () => {
|
||||
console.log('Ready!');
|
||||
});
|
||||
```
|
||||
|
||||
</CH.Code>
|
||||
|
||||
<Alert title="Tip" type="info">
|
||||
- The [`fs`](https://nodejs.org/api/fs.html) module is Node's native file system module. _`readdir`_ is used to read
|
||||
the _`commands`_ directory and identify our command files. - The [`path`](https://nodejs.org/api/path.html) module is
|
||||
Node's native path utility module. _`join`_ helps construct paths to access files and directories. One of the
|
||||
advantages of _`path.join`_ is that it automatically detects the operating system and uses the appropriate joiners. -
|
||||
The [`url`](https://nodejs.org/api/url.html) module provides utilities for URL resolution and parsing.
|
||||
_`fileURLToPath`_ ensuring a cross-platform valid absolute path string.
|
||||
- The{' '}
|
||||
<DocsLink type="class" parent="Collection" /> class extends JavaScript's native
|
||||
[_`Map`_](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) class, and includes
|
||||
more extensive, useful functionality. _`Collection`_ is used to store and efficiently retrieve commands for execution.
|
||||
|
||||
</Alert>
|
||||
|
||||
Next, using the modules imported above, dynamically retrieve your command files with a few more additions to the _`index.js`_ file:
|
||||
|
||||
<CH.Code>
|
||||
|
||||
```js JavaScript focus=3:15
|
||||
const commands = new Collection();
|
||||
|
||||
const commandsPath = fileURLToPath(new URL('commands', import.meta.url));
|
||||
const commandFiles = await readdir(commandsPath).then((files) => files.filter((file) => file.endsWith('.js')));
|
||||
|
||||
for (const file of commandFiles) {
|
||||
const filePath = join(commandsPath, file);
|
||||
const command = await import(filePath);
|
||||
// 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) {
|
||||
commands.set(command.data.name, command);
|
||||
} else {
|
||||
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```ts TypeScript focus=3:15
|
||||
const commands = new Collection<string, CommandModule>();
|
||||
|
||||
const commandsPath = fileURLToPath(new URL('commands', import.meta.url));
|
||||
const commandFiles = await readdir(commandsPath).then((files) => files.filter((file) => file.endsWith('.js')));
|
||||
|
||||
for (const file of commandFiles) {
|
||||
const filePath = join(commandsPath, file);
|
||||
const command = await import(filePath);
|
||||
// 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) {
|
||||
commands.set(command.data.name, command);
|
||||
} else {
|
||||
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
</CH.Code>
|
||||
|
||||
First, [url.fileURLToPath()](https://nodejs.org/api/url.html) helps to construct a path to the _`commands`_ directory. The [fs.readdir()](https://nodejs.org/api/fs.html#fspromisesreaddirpath-options) method then reads the path to the directory and returns a Promise which resolves to an array of all the file names it contains, currently _`['ping.js', 'server.js', 'user.js']`_. To ensure only command files get processed, _`Array.filter()`_ removes any non-JavaScript files from the array.
|
||||
|
||||
With the correct files identified, the last step is to loop over the array and dynamically set each command into the _`commands`_ Collection. For each file being loaded, check that it has at least the _`data`_ and _`execute`_ properties. This helps to prevent errors resulting from loading empty, unfinished or otherwise incorrect command files while you're still developing.
|
||||
|
||||
## Receiving command interactions
|
||||
|
||||
Every slash command is an _`interaction`_, so to respond to a command, you need to create a listener for the <DocsLink type="class" parent="Client" symbol="e-interactionCreate" /> event that will execute code when your application receives an interaction. Place the code below in the _`index.js`_ file you created earlier.
|
||||
|
||||
<CH.Code>
|
||||
|
||||
```js
|
||||
client.on(Events.InteractionCreate, (interaction) => {
|
||||
console.log(interaction);
|
||||
});
|
||||
```
|
||||
|
||||
</CH.Code>
|
||||
|
||||
Not every interaction is a slash command (e.g. _`MessageComponent`_ interactions). Make sure to only handle slash commands in this function by making use of the <DocsLink type="class" parent="BaseInteraction" symbol="isChatInputCommand" brackets /> method to exit the handler if another type is encountered. This method also provides type guarding for TypeScript users, narrowing the type from _`BaseInteraction`_ to <DocsLink type="class" parent="ChatInputCommandInteraction" />.
|
||||
|
||||
<CH.Code>
|
||||
|
||||
```js focus=2
|
||||
client.on(Events.InteractionCreate, (interaction) => {
|
||||
if (!interaction.isChatInputCommand()) return;
|
||||
console.log(interaction);
|
||||
});
|
||||
```
|
||||
|
||||
</CH.Code>
|
||||
|
||||
## Executing commands
|
||||
|
||||
When your bot receives a <DocsLink type="class" parent="Client" symbol="e-interactionCreate" /> event, the interaction object contains all the information you need to dynamically retrieve and execute your commands!
|
||||
|
||||
Let's take a look at the _`ping`_ command again. Note the _`execute()`_ function that will reply to the interaction with "Pong!".
|
||||
|
||||
<CH.Code>
|
||||
|
||||
```js
|
||||
export const data = {
|
||||
name: 'ping',
|
||||
description: 'Replies with Pong!',
|
||||
};
|
||||
|
||||
export async function execute(interaction) {
|
||||
await interaction.reply('Pong!');
|
||||
}
|
||||
```
|
||||
|
||||
</CH.Code>
|
||||
|
||||
First, you need to get the matching command from the _`commands`_ Collection based on the _`interaction.commandName`_. If no matching command is found, log an error to the console and ignore the event.
|
||||
|
||||
With the right command identified, all that's left to do is call the command's _`.execute()`_ method and pass in the _`interaction`_ variable as its argument. Note that the event listener has been made _`async`_, allowing Promises to be awaited. In case something goes wrong and the Promise rejects, catch and log any error to the console.
|
||||
|
||||
<CH.Code>
|
||||
|
||||
```js focus=4:20
|
||||
// focus[37:42]
|
||||
client.on(Events.InteractionCreate, async (interaction) => {
|
||||
if (!interaction.isChatInputCommand()) return;
|
||||
|
||||
const command = commands.get(interaction.commandName);
|
||||
|
||||
if (!command) {
|
||||
console.error(`No command matching ${interaction.commandName} was found.`);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await command.execute(interaction);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
if (interaction.replied || interaction.deferred) {
|
||||
await interaction.followUp({ content: 'There was an error while executing this command!', ephemeral: true });
|
||||
} else {
|
||||
await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
|
||||
}
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
</CH.Code>
|
||||
|
||||
## Command categories
|
||||
|
||||
So far, all of your command files are in a single _`commands`_ folder. This is fine at first, but as your project grows, the number of files in the _`commands`_ folder will too. Keeping track of that many files can be a little tough. To make this a little easier, you can categorize your commands and put them in subfolders inside the _`commands`_ folder. You will have to make a few changes to your existing code in _`index.js`_ for this to work out.
|
||||
|
||||
If you've been following along, your project structure should look something like this:
|
||||
|
||||

|
||||
|
||||
After moving your commands into subfolders, it will look something like this:
|
||||
|
||||

|
||||
|
||||
<Alert title="Warning" type="warning">
|
||||
Make sure you put every command file you have inside one of the new subfolders. Leaving a command file directly under
|
||||
the _`commands`_ folder will create problems.
|
||||
</Alert>
|
||||
|
||||
It is not necessary to name your subfolders exactly like we have named them here. You can create any number of subfolders and name them whatever you want. Although, it is a good practice to name them according to the type of commands stored inside them.
|
||||
|
||||
Back in your _`index.js`_ file, where the code to [dynamically read command files](#loading-command-files) is, use the same pattern to read the subfolder directories, and then require each command inside them.
|
||||
|
||||
<CH.Code>
|
||||
|
||||
```js JavaScript focus=3:7,19
|
||||
const commands = new Collection();
|
||||
|
||||
const foldersPath = fileURLToPath(new URL('commands', import.meta.url));
|
||||
const commandFolders = await readdir(foldersPath);
|
||||
|
||||
for (const folder of commandFolders) {
|
||||
const commandsPath = join(foldersPath, folder);
|
||||
const commandFiles = await readdir(commandsPath).then((files) => files.filter((file) => file.endsWith('.js')));
|
||||
for (const file of commandFiles) {
|
||||
const filePath = join(commandsPath, file);
|
||||
const command = await import(filePath);
|
||||
// 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) {
|
||||
commands.set(command.data.name, command);
|
||||
} else {
|
||||
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```ts Typescript mark=3:7,19
|
||||
const commands = new Collection<string, CommandModule>();
|
||||
|
||||
const foldersPath = fileURLToPath(new URL('commands', import.meta.url));
|
||||
const commandFolders = await readdir(foldersPath);
|
||||
|
||||
for (const folder of commandFolders) {
|
||||
const commandsPath = join(foldersPath, folder);
|
||||
const commandFiles = await readdir(commandsPath).then((files) => files.filter((file) => file.endsWith('.js')));
|
||||
for (const file of commandFiles) {
|
||||
const filePath = join(commandsPath, file);
|
||||
const command = await import(filePath);
|
||||
// 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) {
|
||||
commands.set(command.data.name, command);
|
||||
} else {
|
||||
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
</CH.Code>
|
||||
|
||||
That's it! When creating new files for commands, make sure you create them inside one of the subfolders (or a new one) in the _`commands`_ folder.
|
||||
|
||||
#### Next steps
|
||||
|
||||
Your command files are now loaded into your bot, and the event listener is prepared and ready to respond. In the next section, we cover the final step - a command deployment script you'll need to register your commands so they appear in the Discord client.
|
||||
|
||||
#### Resulting code
|
||||
|
||||
<ResultingCode />
|
||||
|
||||
It also includes some bonus commands!
|
||||
@@ -0,0 +1,155 @@
|
||||
---
|
||||
title: Registering slash commands
|
||||
category: Creating your bot
|
||||
---
|
||||
|
||||
# Registering slash commands
|
||||
|
||||
<Alert title="Read first!" type="info">
|
||||
For fully functional slash commands, you need three important pieces of code:
|
||||
|
||||
1. The [individual command files](slash-commands), containing their definitions and functionality.
|
||||
2. The [command handler](command-handling), which dynamically reads the files and executes the commands.
|
||||
3. The command deployment script, to register your slash commands with Discord so they appear in the interface.
|
||||
|
||||
These steps can be done in any order, but **all are required** before the commands are fully functional.
|
||||
|
||||
This page details how to complete **Step 3**. Make sure to also complete the other pages linked above!
|
||||
|
||||
</Alert>
|
||||
|
||||
## Command registration
|
||||
|
||||
Slash commands can be registered in two ways; in one specific guild, or for every guild the bot is in. We're going to look at single-guild registration first, as this is a good way to develop and test your commands before a global deployment.
|
||||
|
||||
Your application will need the _`applications.commands`_ scope authorized in a guild for any of its slash commands to appear, and to be able to register them in a specific guild without error.
|
||||
|
||||
Slash commands only need to be registered once, and updated when the definition (description, options etc) is changed. As there is a daily limit on command creations, it's not necessary nor desirable to connect a whole client to the gateway or do this on every _`ClientReady`_ event. As such, a standalone script using the lighter REST manager is preferred.
|
||||
|
||||
This script is intended to be run separately, only when you need to make changes to your slash command **definitions** - you're free to modify parts such as the execute function as much as you like without redeployment.
|
||||
|
||||
### Guild commands
|
||||
|
||||
Create a _`deploy-commands.js`_ file in your project directory. This file will be used to register and update the slash commands for your bot application.
|
||||
|
||||
Add two more properties to your _`config.json`_ file, which we'll need in the deployment script:
|
||||
|
||||
- _`clientId`_: Your application's client id ([Discord Developer Portal](https://discord.com/developers/applications) > "General Information" > application id)
|
||||
- _`guildId`_: Your development server's id ([Enable developer mode](https://support.discord.com/hc/en-us/articles/206346498) > Right-click the server title > "Copy Server ID")
|
||||
|
||||
<CH.Code lineNumbers={false}>
|
||||
|
||||
```json
|
||||
{
|
||||
"token": "your-token-goes-here",
|
||||
"clientId": "your-application-id-goes-here",
|
||||
"guildId": "your-server-id-goes-here"
|
||||
}
|
||||
```
|
||||
|
||||
</CH.Code>
|
||||
|
||||
With these defined, you can use the deployment script below:
|
||||
|
||||
<CH.Code>
|
||||
|
||||
```js deploy-commands.js
|
||||
import { REST, Routes } from 'discord.js';
|
||||
import { readdir } from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import config from './config.json' assert { type: 'json' };
|
||||
|
||||
const { clientId, guildId, token } = config;
|
||||
|
||||
const commands = [];
|
||||
|
||||
// Grab all the command files from the commands directory you created earlier
|
||||
const foldersPath = fileURLToPath(new URL('commands', import.meta.url));
|
||||
const commandFolders = await readdir(foldersPath);
|
||||
|
||||
for (const folder of commandFolders) {
|
||||
// Grab all the command files from the commands directory you created earlier
|
||||
const commandsPath = join(foldersPath, folder);
|
||||
const commandFiles = await readdir(commandsPath).then((files) => files.filter((file) => file.endsWith('.js')));
|
||||
// Grab the SlashCommandBuilder#toJSON() output of each command's data for deployment
|
||||
for (const file of commandFiles) {
|
||||
const filePath = join(commandsPath, file);
|
||||
const 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);
|
||||
|
||||
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);
|
||||
}
|
||||
```
|
||||
|
||||
</CH.Code>
|
||||
|
||||
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!
|
||||
|
||||
### Global commands
|
||||
|
||||
Global application commands will be available in all the guilds your application has the _`applications.commands`_ scope authorized in, and in direct messages by default.
|
||||
|
||||
To deploy global commands, you can use the same script from the [guild commands](#guild-commands) section and simply adjust the route in the script to _`.applicationCommands(clientId)`_
|
||||
|
||||
Test
|
||||
|
||||
<CH.Code rows="focus">
|
||||
|
||||
```js focus=5
|
||||
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.applicationCommands(clientId), { 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);
|
||||
}
|
||||
```
|
||||
|
||||
</CH.Code>
|
||||
|
||||
### Where to deploy
|
||||
|
||||
<Alert title="Tip" type="success">
|
||||
Guild-based deployment of commands is best suited for development and testing in your own personal server. Once you're satisfied that it's ready, deploy the command globally to publish it to all guilds that your bot is in.
|
||||
|
||||
You may wish to have a separate application and token in the Discord Dev Portal for your dev application, to avoid duplication between your guild-based commands and the global deployment.
|
||||
|
||||
</Alert>
|
||||
|
||||
#### Further reading
|
||||
|
||||
You've successfully sent a response to a slash command! However, this is only the most basic of command event and response functionality. Much more is available to enhance the user experience including:
|
||||
|
||||
- applying this same dynamic, modular handling approach to events with an [Event handler](./event-handling).
|
||||
- utilising the different [Response methods](../slash-commands/response-methods) that can be used for slash commands.
|
||||
- expanding on these examples with additional validated option types in [Advanced command creation](../slash-commands/advanced-creation).
|
||||
- adding formatted [Embeds](../popular-topics/embeds) to your responses.
|
||||
- enhancing the command functionality with [Buttons](../interactions/buttons) and [Select Menus](../interactions/select-menus).
|
||||
- prompting the user for more information with [Modals](../interactions/modals).
|
||||
|
||||
#### Resulting code
|
||||
|
||||
<ResultingCode path="creating-your-bot/command-deployment" />
|
||||
@@ -0,0 +1,219 @@
|
||||
---
|
||||
title: Event handling
|
||||
category: Creating your bot
|
||||
---
|
||||
|
||||
# Event handling
|
||||
|
||||
Node.js uses an event-driven architecture, making it possible to execute code when a specific event occurs. The discord.js library takes full advantage of this. You can visit the <DocsLink type="class" parent="Client" /> documentation to see the full list of events.
|
||||
|
||||
<Alert title="Tip" type="success">
|
||||
This page assumes you've followed the guide up to this point, and created your _`index.js`_ and individual slash
|
||||
commands according to those pages.
|
||||
</Alert>
|
||||
|
||||
At this point, your `index.js` file has code for loading commands, and listeners for two events: `ClientReady` and `InteractionCreate`.
|
||||
|
||||
<CH.Code>
|
||||
|
||||
```js Commands
|
||||
const commands = new Collection();
|
||||
|
||||
const foldersPath = fileURLToPath(new URL('commands', import.meta.url));
|
||||
const commandFolders = await readdir(foldersPath);
|
||||
|
||||
for (const folder of commandFolders) {
|
||||
const commandsPath = join(foldersPath, folder);
|
||||
const commandFiles = await readdir(commandsPath).then((files) => files.filter((file) => file.endsWith('.js')));
|
||||
for (const file of commandFiles) {
|
||||
const filePath = join(commandsPath, file);
|
||||
const command = await import(filePath);
|
||||
// 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) {
|
||||
commands.set(command.data.name, command);
|
||||
} else {
|
||||
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```js ClientReady
|
||||
client.once(Events.ClientReady, (c) => {
|
||||
console.log(`Ready! Logged in as ${c.user.tag}`);
|
||||
});
|
||||
```
|
||||
|
||||
```js InteractionCreate
|
||||
client.on(Events.InteractionCreate, async (interaction) => {
|
||||
if (!interaction.isChatInputCommand()) return;
|
||||
|
||||
const command = commands.get(interaction.commandName);
|
||||
|
||||
if (!command) {
|
||||
console.error(`No command matching ${interaction.commandName} was found.`);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await command.execute(interaction);
|
||||
} catch (error) {
|
||||
console.error(`Error executing ${interaction.commandName}`);
|
||||
console.error(error);
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
</CH.Code>
|
||||
|
||||
Currently, all of this code is in the _`index.js`_ file. <DocsLink type="class" parent="Client" symbol="e-ready" /> emits once when the _`Client`_ becomes ready for use, and <DocsLink type="class" parent="Client" symbol="e-interactionCreate" /> emits whenever an interaction is received.
|
||||
Moving the event listener code into individual files is simple, and we'll be taking a similar approach to the [command handler](./handling-command-interactions).
|
||||
|
||||
## Individual event files
|
||||
|
||||
Your project directory should look something like this:
|
||||
|
||||
```
|
||||
discord-bot/
|
||||
├── commands/
|
||||
├── node_modules/
|
||||
├── config.json
|
||||
├── deploy-commands.js
|
||||
├── index.js
|
||||
├── package-lock.json
|
||||
└── package.json
|
||||
```
|
||||
|
||||
Create an _`events`_ folder in the same directory. You can then move the code from your event listeners in _`index.js`_ to separate files: _`events/ready.js`_ and _`events/interactionCreate.js`_. The _`InteractionCreate`_ event is responsible for command handling, so the command loading code will move here too.
|
||||
|
||||
<CH.Code>
|
||||
|
||||
```js events/interactionCreate.js
|
||||
import { readdir } from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { Collection, Events } from 'discord.js';
|
||||
|
||||
const commands = new Collection();
|
||||
|
||||
const foldersPath = fileURLToPath(new URL('commands', import.meta.url));
|
||||
const commandFolders = await readdir(foldersPath);
|
||||
|
||||
for (const folder of commandFolders) {
|
||||
const commandsPath = join(foldersPath, folder);
|
||||
const commandFiles = await readdir(commandsPath).then((files) => files.filter((file) => file.endsWith('.js')));
|
||||
for (const file of commandFiles) {
|
||||
const filePath = join(commandsPath, file);
|
||||
const command = await import(filePath);
|
||||
// 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) {
|
||||
commands.set(command.data.name, command);
|
||||
} else {
|
||||
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const data = {
|
||||
name: Events.InteractionCreate,
|
||||
};
|
||||
|
||||
export async function execute(interaction) {
|
||||
if (!interaction.isChatInputCommand()) return;
|
||||
|
||||
const command = commands.get(interaction.commandName);
|
||||
|
||||
if (!command) {
|
||||
console.error(`No command matching ${interaction.commandName} was found.`);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await command.execute(interaction);
|
||||
} catch (error) {
|
||||
console.error(`Error executing ${interaction.commandName}`);
|
||||
console.error(error);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```js events/ready.js
|
||||
import { Events } from 'discord.js';
|
||||
|
||||
export const data = {
|
||||
name: Events.ClientReady,
|
||||
once = true,
|
||||
};
|
||||
export async function execute(client) {
|
||||
console.log(`Ready! Logged in as ${client.user.tag}`);
|
||||
}
|
||||
```
|
||||
|
||||
```js index.js
|
||||
import { readdir } from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { Client, GatewayIntentBits } from 'discord.js';
|
||||
import config from './config.json' assert { type: 'json' };
|
||||
|
||||
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
|
||||
|
||||
client.login(config.token);
|
||||
```
|
||||
|
||||
</CH.Code>
|
||||
|
||||
The _`name`_ property states which event this file is for, and the _`once`_ property holds a boolean value that specifies if the event should run only once. You don't need to specify this in _`interactionCreate.js`_ as the default behavior will be to run on every event instance. The _`execute`_ function holds your event logic, which will be called by the event handler whenever the event emits.
|
||||
|
||||
## Reading event files
|
||||
|
||||
Next, let's write the code for dynamically retrieving all the event files in the _`events`_ folder. We'll be taking a similar approach to our [command handler](./handling-command-interactions). Place the new code highlighted below in your _`index.js`_.
|
||||
|
||||
_`fs.readdir()`_ combined with _`array.filter()`_ returns an array of all the file names in the given directory and filters for only _`.js`_ files, i.e. _`['ready.js', 'interactionCreate.js']`_.
|
||||
|
||||
<CH.Code>
|
||||
|
||||
```js focus=9:20
|
||||
import { readdir } from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { Client, GatewayIntentBits } from 'discord.js';
|
||||
import config from './config.json' assert { type: 'json' };
|
||||
|
||||
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
|
||||
|
||||
const eventsPath = fileURLToPath(new URL('events', import.meta.url));
|
||||
const eventFiles = await readdir(eventsPath).then((files) => files.filter((file) => file.endsWith('.js')));
|
||||
|
||||
for (const file of eventFiles) {
|
||||
const filePath = join(eventsPath, file);
|
||||
const event = await import(filePath);
|
||||
if (event.data.once) {
|
||||
client.once(event.data.name, (...args) => event.execute(...args));
|
||||
} else {
|
||||
client.on(event.data.name, (...args) => event.execute(...args));
|
||||
}
|
||||
}
|
||||
|
||||
client.login(config.token);
|
||||
```
|
||||
|
||||
</CH.Code>
|
||||
|
||||
You'll notice the code looks very similar to the command loading above it - read the files in the events folder and load each one individually.
|
||||
|
||||
The <DocsLink type="class" parent="Client" /> class in discord.js extends the [`EventEmitter`](https://nodejs.org/api/events.html#events_class_eventemitter) class. Therefore, the _`client`_ object exposes the [`.on()`](https://nodejs.org/api/events.html#events_emitter_on_eventname_listener) and [`.once()`](https://nodejs.org/api/events.html#events_emitter_once_eventname_listener) methods that you can use to register event listeners. These methods take two arguments: the event name and a callback function. These are defined in your separate event files as _`name`_ and _`execute`_.
|
||||
|
||||
The callback function passed takes argument(s) returned by its respective event, collects them in an _`args`_ array using the _`...`_ [rest parameter syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters), then calls _`event.execute()`_ while passing in the _`args`_ array using the _`...`_ [spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax). They are used here because different events in discord.js have different numbers of arguments. The rest parameter collects these variable number of arguments into a single array, and the spread syntax then takes these elements and passes them to the _`execute`_ function.
|
||||
|
||||
After this, listening for other events is as easy as creating a new file in the _`events`_ folder. The event handler will automatically retrieve and register it whenever you restart your bot.
|
||||
|
||||
<Alert title="Tip" type="success">
|
||||
In most cases, you can access your _`client`_ instance in other files by obtaining it from one of the other discord.js
|
||||
structures, e.g. _`interaction.client`_ in the _`InteractionCreate`_ event. You do not need to manually pass it to
|
||||
your events.
|
||||
</Alert>
|
||||
|
||||
## Resulting code
|
||||
|
||||
<ResultingCode />
|
||||