Compare commits

...

65 Commits

Author SHA1 Message Date
iCrawl
3665ad65d0 chore(ws): release @discordjs/ws@0.8.2 2023-05-01 17:34:27 +02:00
iCrawl
d4de1cd09e chore(proxy): release @discordjs/proxy@1.4.1 2023-05-01 17:31:00 +02:00
iCrawl
481bbc924f chore(rest): release @discordjs/rest@1.7.1 2023-05-01 17:29:19 +02:00
iCrawl
ca81e61b4c chore(formatters): release @discordjs/formatters@0.3.1 2023-05-01 17:24:36 +02:00
iCrawl
eb603c0d11 chore(util): release @discordjs/util@0.3.0 2023-05-01 17:22:55 +02:00
iCrawl
072c9da5df chore(collection): release @discordjs/collection@1.5.1 2023-05-01 17:20:16 +02:00
iCrawl
cd591327d6 chore(builders): release @discordjs/builders@1.6.2 2023-05-01 17:16:31 +02:00
iCrawl
71e67d8c97 chore(brokers): release @discordjs/brokers@0.2.1 2023-05-01 17:15:29 +02:00
Qjuh
a9e0de4288 refactor(WebSocketManager): use /ws package internally (#9099) 2023-05-01 17:08:23 +02:00
iCrawl
c5b4423a5a ci: properly add all tsconfig options 2023-05-01 16:44:36 +02:00
iCrawl
47b08be509 ci: fix start scripts for actions 2023-05-01 16:34:56 +02:00
iCrawl
2e0804ae92 ci: update node version 2023-05-01 16:27:29 +02:00
iCrawl
71983cc5d1 ci: make package optional for docs upload 2023-05-01 16:02:05 +02:00
iCrawl
0f3d870ce6 ci: properly look for docs 2023-05-01 15:57:28 +02:00
iCrawl
ce4e1fc2c6 ci: dramatically speed up docs building 2023-05-01 15:55:14 +02:00
iCrawl
0762ddb3f4 chore: deps 2023-05-01 15:29:51 +02:00
iCrawl
80af9696d3 build: leftover extensions 2023-05-01 15:23:15 +02:00
iCrawl
48cab844d4 build: switch to bundler moduleResolution 2023-05-01 13:14:13 +02:00
iCrawl
8b71f44b1f chore: deps 2023-05-01 12:05:55 +02:00
Almeida
f27631175a feat(ui): support embed image, thumbnail, author url, and url (#9478) 2023-04-30 16:56:34 +02:00
GrapeColor
ad217cc760 fix(ShardClientUtil): Fix client event names (#9474)
Co-authored-by: GrapeColor <grapecolor@users.noreply.github.com>
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2023-04-30 10:16:44 +00:00
iCrawl
1ba7394a7d chore: deps 2023-04-30 09:01:17 +02:00
Jiralite
260c46d51c feat(guide): Add audit logs (#9429) 2023-04-30 07:50:14 +02:00
iCrawl
6229597db2 fix(guide): add more headings 2023-04-29 20:10:06 +02:00
iCrawl
8d212e4859 feat(guide): anchor links 2023-04-29 20:05:22 +02:00
iCrawl
51e8f02ef7 fix(ui): author and reply author spacing 2023-04-29 17:44:02 +02:00
Tetie
496c4e2884 feat(ui): support verified bots and colored authors (#9471)
Co-authored-by: Noel <buechler.noel@outlook.com>
2023-04-29 17:26:31 +02:00
Jiralite
77191a2e7b docs: Add new issue form for applications (#9470) 2023-04-28 21:47:19 +02:00
Jiralite
375483b0f9 feat(guide): Add threads (#9430) 2023-04-28 21:46:45 +02:00
Jiralite
17cd4b610a fix(guide): Show rest of TypeScript code block (#9465) 2023-04-28 21:46:27 +02:00
Suneet Tipirneni
988f8c7546 refactor(website): consolidate styling for buttons (#9466) 2023-04-28 21:42:47 +02:00
Jiralite
217e5d8100 fix(BaseClient): Prevent user agent mutation (#9425)
fix(BaseClient): prevent user agent mutation
2023-04-28 17:46:50 +00:00
Jaw0r3k
40d07fbbbd fix(BitField): use only enum names in iterating (#9357)
* fix: use only names in iterating bitfield

* fix: not a number

Co-authored-by: Vlad Frangu <kingdgrizzle@gmail.com>

* fix: serialize

Co-authored-by: SpaceEEC <spaceeec@yahoo.com>

---------

Co-authored-by: Vlad Frangu <kingdgrizzle@gmail.com>
Co-authored-by: SpaceEEC <spaceeec@yahoo.com>
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2023-04-28 17:25:11 +00:00
anandre
1b15d31b5a docs(AutoModerationRule): update docs (#9464)
* Update AutoModerationRule.js

Update the docs descriptions for some of the AutoModerationRule methods to make them clearer and easier to understand

* Update AutoModerationRule.js

Updated the `exemptRoles` and `exemptChannels` parameter descriptions for their respective helper methods to match the typedef `AutoModerationRuleEditOptions`.

* Update AutoModerationRule.js

Update the `mentionTotalLimit` description to match the one in the `AutoModerationTriggerMetadataOptions` typdef.

* Update packages/discord.js/src/structures/AutoModerationRule.js

Co-authored-by: Jiralite <33201955+Jiralite@users.noreply.github.com>

---------

Co-authored-by: Jiralite <33201955+Jiralite@users.noreply.github.com>
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2023-04-28 17:19:14 +00:00
Idris
d26df5faba types(AutoModerationActionMetadataOptions): make channel property optional (#9460)
* refactor(GuildMember): make _roles a getter and roles a normal prop

* types(AutoModerationActionMetadataOptions): make channel property optional

* fix: revert changes from another PR

---------

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2023-04-28 17:13:27 +00:00
Ryan Munro
78fe247fc4 feat(guide): port and update lots of stuff (#9385)
Co-authored-by: Jiralite <33201955+Jiralite@users.noreply.github.com>
Co-authored-by: Noel <buechler.noel@outlook.com>
2023-04-27 20:58:25 +02:00
RanAS
36216c0e1a docs: include StreamType enum description in new docs (#9457) 2023-04-27 20:29:27 +02:00
Jiralite
6212bffa30 docs: Update example usage (#9461) 2023-04-27 20:28:44 +02:00
Suneet Tipirneni
b2e1bb92d0 fix(website): don't duplicate overloaded methods (#9462) 2023-04-27 20:25:23 +02:00
Almeida
2e09cb4c1f feat(ui): support embed fields, footer icon, and timestamp (#9442) 2023-04-25 19:05:14 +02:00
Michael H
1b4d34cebf chore: Add directory to package.json (#9456)
* chore: Add directory to package.json

* fix: run fmt

* fix: undo formatting
2023-04-25 14:27:44 +00:00
iCrawl
8153ca99ee ci: update formatting tag 2023-04-24 20:19:40 +02:00
iCrawl
43e205b840 chore: deps 2023-04-24 19:46:44 +02:00
Jiralite
c6ca5a83e7 docs(APITypes): Document role & user select menu components (#9435)
docs(APITypes): document select menu components

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2023-04-21 20:56:51 +00:00
Jiralite
5c52bb9590 docs(BaseMessageOptions): Fix embeds and components (#9437)
docs(BaseMessageOptions): fix embeds and components

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2023-04-21 20:43:17 +00:00
DD
a49ed0a2d5 refactor(proxy): rely on auth header instead (#9422)
* refactor(proxy): rely on auth header instead

* chore: typo

* chore: language

Co-authored-by: Jiralite <33201955+Jiralite@users.noreply.github.com>

* chore: more language

Co-authored-by: Aura Román <kyradiscord@gmail.com>

* chore: more language nitpicks

Co-authored-by: ckohen <chaikohen@gmail.com>

* fix: unnecessary async

---------

Co-authored-by: Jiralite <33201955+Jiralite@users.noreply.github.com>
Co-authored-by: Aura Román <kyradiscord@gmail.com>
Co-authored-by: ckohen <chaikohen@gmail.com>
2023-04-21 20:36:15 +00:00
Almeida
3e01f91bbb feat(Attachment): voice messages (#9392)
Co-authored-by: Tetie <tjvssr@gmail.com>
2023-04-21 11:09:37 +02:00
anandre
7d341000d4 docs(InteractionResponses): showModal docs change (#9434)
* Update InteractionResponses.js

Update the parameters for the showModal method

* Update APITypes.js

Add APIModalInteractionResponseCallbackData link for docs link for showModal method

* Update InteractionResponses.js

Change the order of parameters so the ModalBuilder is listed first

* Update APITypes.js

Disable the ESline line length rule for the APITypes file

* Update InteractionResponses.js

Add ModalComponentData to the JSDoc, it was omitted before.
2023-04-21 08:17:44 +00:00
Jiralite
b49c5c9f48 ci: Fix issue triage (#9433) 2023-04-20 20:41:21 +02:00
MrMythicalYT
ce287f21d1 docs: use ESM code in examples (#9427)
* docs(Partials): use import statement

* docs: update readme to ESM

---------

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2023-04-20 06:40:15 +00:00
MrMythicalYT
d6bca9bb4d docs: reference package names properly (#9426) 2023-04-20 06:25:32 +00:00
Jiralite
a2ab2b8717 feat(scripts): Sort issue labels (#9423)
feat(scripts): sort issue labels

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2023-04-19 20:09:05 +00:00
Suneet Tipirneni
ecd1b5da11 refactor(website): consolidate badge logic (#9417)
Co-authored-by: Noel <buechler.noel@outlook.com>
2023-04-19 18:58:35 +02:00
Jiralite
0eb866357b ci: Update actions (#9424) 2023-04-19 18:57:16 +02:00
Almeida
d2d27ce734 fix: use new permission name (#9274)
* fix: use new permission name

* docs: requested changes

---------

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2023-04-19 14:32:07 +00:00
Jiralite
603446a692 chore: Bump dependencies for template package (#9418)
* chore: bump dependencies

* chore: update .yarnrc.yml
2023-04-19 05:43:46 +00:00
Suneet Tipirneni
f1fdd5b010 refactor(website): extract shared code heading styling into component (#9414)
* refactor(website): extract shared code heading styling into component

* chore: remove redundant variable
2023-04-17 21:33:51 +00:00
DD
5d1a4c27d5 feat(core): abstract gateway (#9410)
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2023-04-17 20:05:05 +00:00
iCrawl
98a76db482 docs: generate static imports for types with api-extractor 2023-04-17 19:08:01 +02:00
Suneet Tipirneni
516c46117c feat(website): use tsdoc parameter names wherever possible (#9413)
Co-authored-by: Noel <buechler.noel@outlook.com>
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2023-04-17 18:44:17 +02:00
Tetie
7d7972d239 chore(Client): robust error checking (#9390)
* chore: robust error checking

* fix: check for null

* chore: add period

Co-authored-by: Jiralite <33201955+Jiralite@users.noreply.github.com>

* fix: check for undefined correctly

* chore: robust error checking

* fix: check for null

* chore: add period

Co-authored-by: Jiralite <33201955+Jiralite@users.noreply.github.com>

* fix: check for undefined correctly

* fix: check for null

* fix: update typings

---------

Co-authored-by: Jiralite <33201955+Jiralite@users.noreply.github.com>
2023-04-17 15:05:32 +00:00
Jiralite
7b10e8cb63 feat: Add FAQ (#9407)
* feat: port over FAQ

* refactor: use async/await

Co-authored-by: Almeida <almeidx@pm.me>

* style: spacing

* refactor: use role id

* feat: more links!

* refactor: move comment up

* refactor: consistent naming style

---------

Co-authored-by: Almeida <almeidx@pm.me>
2023-04-17 08:31:53 +00:00
Jiralite
2f18323d2c fix(updating-to-v14): Parameter typo (#9408)
fix: parameter typo
2023-04-17 01:35:34 +00:00
Suneet Tipirneni
e04801bba1 fix(website): add equals to enum members (#9405) 2023-04-16 21:43:37 +00:00
iCrawl
09a9fb57e0 chore(core): release @discordjs/core@0.5.2 2023-04-16 23:02:41 +02:00
191 changed files with 5811 additions and 4152 deletions

View 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:
@@ -29,57 +31,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 +79,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 +97,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 +124,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)

View 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

View File

@@ -9,11 +9,13 @@ 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
@@ -48,7 +50,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.

View File

@@ -1,24 +1,42 @@
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: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: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"

View File

@@ -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:
@@ -130,7 +65,7 @@ jobs:
tag: ${{ github.ref_name }}
- 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
@@ -139,17 +74,16 @@ jobs:
version: ${{ steps.extract-tag.outputs.semver }}
- name: Move docs to correct directory
if: ${{ github.ref_type == 'tag' && matrix.package == steps.extract-tag.outputs.package }}
if: ${{ github.ref_type == 'tag' }}
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
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
@@ -157,21 +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' }}
env:
PACKAGE: ${{ matrix.package }}
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
fi
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: |

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -43,10 +43,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

View File

@@ -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

View File

@@ -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

View File

@@ -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

View 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"
}

View File

@@ -15,4 +15,4 @@ yarnPath: .yarn/releases/yarn-3.5.0.cjs
packageExtensions:
'@storybook/core-common@*':
dependencies:
'@storybook/react-vite': '7.0.5'
'@storybook/react-vite': '7.0.7'

View File

@@ -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.

View File

@@ -1,9 +1,9 @@
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';
@@ -36,33 +36,31 @@ export const Content = defineDocumentType(() => ({
},
}));
// 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',
@@ -71,31 +69,26 @@ export default makeSource({
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-none 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)),
],
},
],
],
},
});

View File

@@ -16,7 +16,7 @@
"dev:next": "next dev",
"dev:css": "yarn generate:css --watch",
"dev:contentlayer": "contentlayer dev",
"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"
@@ -37,7 +37,8 @@
],
"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"
@@ -47,14 +48,14 @@
"@code-hike/mdx": "^0.8.2",
"@discordjs/ui": "workspace:^",
"@react-icons/all-files": "^4.1.0",
"@vercel/analytics": "^0.1.11",
"@vercel/edge-config": "^0.1.7",
"@vercel/og": "^0.5.2",
"@vercel/analytics": "^1.0.0",
"@vercel/edge-config": "^0.1.8",
"@vercel/og": "^0.5.4",
"ariakit": "^2.0.0-next.44",
"cmdk": "^0.2.0",
"contentlayer": "^0.3.1",
"next": "^13.3.0",
"next-contentlayer": "^0.3.1",
"contentlayer": "^0.3.2",
"next": "^13.3.4",
"next-contentlayer": "^0.3.2",
"next-themes": "^0.2.1",
"react": "^18.2.0",
"react-custom-scrollbars-2": "^4.5.0",
@@ -66,34 +67,35 @@
"rehype-slug": "^5.1.0",
"remark-gfm": "^3.0.1",
"server-only": "^0.0.1",
"sharp": "^0.32.0"
"sharp": "^0.32.1"
},
"devDependencies": {
"@next/bundle-analyzer": "^13.3.0",
"@next/bundle-analyzer": "^13.3.4",
"@testing-library/react": "^14.0.0",
"@testing-library/user-event": "^14.4.3",
"@types/node": "18.15.11",
"@types/react": "^18.0.35",
"@types/react-dom": "^18.0.11",
"@unocss/cli": "^0.51.4",
"@unocss/eslint-config": "^0.51.4",
"@unocss/reset": "^0.51.4",
"@vitejs/plugin-react": "^3.1.0",
"@types/html-escaper": "^3.0.0",
"@types/node": "18.16.3",
"@types/react": "^18.2.0",
"@types/react-dom": "^18.2.1",
"@unocss/cli": "^0.51.8",
"@unocss/eslint-config": "^0.51.8",
"@unocss/reset": "^0.51.8",
"@vitejs/plugin-react": "^4.0.0",
"@vitest/coverage-c8": "^0.30.1",
"concurrently": "^8.0.1",
"cross-env": "^7.0.3",
"eslint": "^8.38.0",
"eslint": "^8.39.0",
"eslint-config-neon": "^0.1.42",
"eslint-formatter-pretty": "^5.0.0",
"happy-dom": "^9.7.1",
"happy-dom": "^9.10.1",
"hast-util-to-string": "^2.0.0",
"hastscript": "^7.2.0",
"html-escaper": "^3.0.3",
"lighthouse": "^10.1.1",
"prettier": "^2.8.7",
"prettier": "^2.8.8",
"typescript": "^5.0.4",
"unocss": "^0.51.4",
"vercel": "^28.18.5",
"unocss": "^0.51.8",
"vercel": "^29.0.3",
"vitest": "^0.29.8"
},
"engines": {

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.0 KiB

View 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>
);
}

View 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>
);
}

View 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>
);
}

View 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>
);
}

View File

@@ -2,6 +2,10 @@
import { Alert, Section, DiscordMessages, DiscordMessage, DiscordMessageEmbed } from '@discordjs/ui';
import { useMDXComponent } from 'next-contentlayer/hooks';
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';
@@ -10,7 +14,19 @@ export function Mdx({ code }: { code: string }) {
return (
<Component
components={{ Alert, Section, DiscordMessages, DiscordMessage, DiscordMessageEmbed, DocsLink, ResultingCode }}
components={{
Alert,
Section,
DiscordMessages,
DiscordMessage,
DiscordMessageEmbed,
DocsLink,
ResultingCode,
h1: H1,
h2: H2,
h3: H3,
h4: H4,
}}
/>
);
}

View File

@@ -136,6 +136,27 @@ Whenever some text does not need to be in the main body, you can put it here.
>
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

View File

@@ -1,231 +0,0 @@
---
title: Initial files
category: Creating your bot
---
# Initial files
Once you [add your bot to a server](preparations/adding-your-bot-to-servers.md), the next step is to start coding and get it online! Let's start by initializing your package.json, creating a config file for your client token, and a main file for your bot application.
## Creating package.json
This command creates a _`package.json`_ file for you, which will keep track of the dependencies your project uses, as well as other information.
<CH.Code>
```sh npm
npm init -y; npm pkg set type="module"
```
```sh yarn
yarn add dotenv
# You must go into your package.json file and add "type": "module"
```
```sh pnpm
pnpm init; pnpm pkg set type="module"
```
</CH.Code>
Once you're done with that, onto the next step!
## Using config.json
As explained in the ["What is a token, anyway?"](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.
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.
<CH.Code>
```json config.json
{
"token": "your-token-goes-here"
}
```
</CH.Code>
You can then access your token inside other files by using _`import`_.
<CH.Code>
```ts
import config from './config.json' assert { type: 'json' };
console.log(config.token);
```
</CH.Code>
<Alert title="Caution" type="danger">
If you're using Git, you should not commit this file and should [ignore it via
_`.gitignore`_](/creating-your-bot/#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>
```shellscript Command line
A=123 B=456 DISCORD_TOKEN=your-token-goes-here node index.js
```
---
```js Usage
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, preload the package to load your _`.env`_ file and attach the variables to _`process.env`_:
##### Installing dotenv
<CH.Code>
```sh npm
npm install dotenv
```
```sh yarn
yarn add dotenv
```
```sh pnpm
pnpm add dotenv
```
</CH.Code>
##### Defining your variables
<CH.Code>
```text .env
A=123
B=456
DISCORD_TOKEN=your-token-goes-here
```
</CH.Code>
<Alert title="Caution" type="danger">
If you're using Git, you should not commit this file and should [ignore it via
_`.gitignore`_](/creating-your-bot/#git-and-gitignore).
</Alert>
##### Utilizing your variables
<CH.Code>
```sh node
node --require dotenv/config yourFile.js
```
```sh yarn
yarn node --require dotenv/config yourFile.js
```
---
```ts yourFile
console.log(process.env.A); // 123
console.log(process.env.B); // 456
console.log(process.env.DISCORD_TOKEN); // your-token-goes-here
```
</CH.Code>
<Section title="Online editors (Glitch, Heroku, Replit, etc.)" defaultClosed padded background gutter>
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)
</Section>
### 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:
<CH.Code>
```
node_modules
.env
config.json
```
</CH.Code>
<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>
## Creating the main file
Open your code editor and create a new file. We suggest that you save the file as _`index.ts`_, or _`index.js`_, depending on whether you use TypeScript. You may name it whatever you wish, however.
Here's the base code to get you started:
<CH.Code>
```ts index.ts
// Import the necessary structures.
import { Client, Events, GatewayIntentBits } from 'discord.js';
import config from './config.json';
// Create a new client instance.
const client = new Client({ intents: GatewayIntentBits.Guilds });
// When the client is ready, run this code (only once).
client.once(Events.ClientReady, () => {
console.log('Ready!');
});
// 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 login to Discord. The _`GatewayIntentBits.Guilds`_ intents option is necessary for your client to work properly, as it ensures that the caches for guilds, channels and roles are populated and available for internal use.
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).
Open your terminal, compile your code (JavaScript users do not do this), and run _`node index.js`_ to start the process. If you see "Ready!" after a few seconds, you're good to go!
<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 <kbd>⌃ Control</kbd>{' '}
<kbd>C</kbd>, you can press <kbd>↑</kbd> on your keyboard to bring up the latest commands you've run. Pressing{' '}
<kbd>↑</kbd> then <kbd>⏎ Enter</kbd> after closing the process is a quick way to start it up again.
</Alert>
## Resulting code
<ResultingCode path="creating-your-bot/initial-files" />
Code is indeed a result of code. That being said, it's being worked on. With code. Definitely.

View File

@@ -1,246 +0,0 @@
---
title: Creating commands
category: Creating your bot
---
# Creating commands
<Alert title="Tip" type="success">
This page is a follow-up and bases its code on [the previous page](/creating-your-bot/).
</Alert>
<DiscordMessages rounded>
<DiscordMessage
interaction={{
author: {
avatar:
'https://cdn.discordapp.com/guilds/222078108977594368/users/81440962496172032/avatars/c059c5d04d717ea05790f7a6447e4843.webp?size=160',
username: 'Crawl',
},
command: 'ping',
}}
author={{
avatar:
'https://cdn.discordapp.com/guilds/222078108977594368/users/81440962496172032/avatars/c059c5d04d717ea05790f7a6447e4843.webp?size=160',
username: 'Crawl',
time: 'Today at 21:00',
}}
>
Pong!
</DiscordMessage>
</DiscordMessages>
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. Before being able to reply to a command, you must first register it.
## Registering commands
This section will cover only the bare minimum to get you started, but you can refer to our [in-depth page on registering slash commands](/interactions/slash-commands.md#registering-slash-commands) for further details. It covers guild commands, global commands, options, option types, and choices.
### Command deployment script
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.
Since commands only need to be registered once, and updated when the definition (description, options etc) is changed, it's not necessary to connect a whole client to the gateway or do this on every _`ready`_ event. As such, a standalone script using the lighter REST manager is preferred.
Below is a deployment script you can use. Focus on these variables:
- _`clientId`_: Your application's client id
- _`guildId`_: Your development server's id
- _`commands`_: An array of commands to register. The [slash command builder](/popular-topics/builders.md#slash-command-builders) from _`discord.js`_ is used to build the data for your commands
<Alert title="Tip" type="success">
In order to get your application's client id, go to [Discord Developer
Portal](https://discord.com/developers/applications) and choose your application. Find the id under "Application ID"
in General Information subpage. To get guild id, open Discord and go to your settings. On the "Advanced" page, turn on
"Developer Mode". This will enable a "Copy ID" button in the context menu when you right-click on a server icon, a
user's profile, etc.
</Alert>
<CH.Code>
```js deploy-commands.js mark=4,6:10
const { REST, SlashCommandBuilder, Routes } = require('discord.js');
const { clientId, guildId, token } = require('./config.json');
const commands = [
new SlashCommandBuilder().setName('ping').setDescription('Replies with pong!'),
new SlashCommandBuilder().setName('server').setDescription('Replies with server info!'),
new SlashCommandBuilder().setName('user').setDescription('Replies with user info!'),
].map((command) => command.toJSON());
const rest = new REST({ version: '10' }).setToken(token);
rest
.put(Routes.applicationGuildCommands(clientId, guildId), { body: commands })
.then((data) => console.log(`Successfully registered ${data.length} application commands.`))
.catch(console.error);
```
---
```json config.json mark=2:3
{
"clientId": "123456789012345678",
"guildId": "876543210987654321",
"token": "your-token-goes-here"
}
```
</CH.Code>
Once you fill in these values, run _`node deploy-commands.js`_ in your project directory to register your commands to a single guild. It's also possible to [register commands globally](/interactions/slash-commands.md#global-commands).
<Alert title="Tip" type="success">
You only need to run `node deploy-commands.js` once. You should only run it again if you add or edit existing
commands.
</Alert>
## Replying to commands
Once you've registered your commands, you can listen for interactions via <DocsLink type="class" parent="Client" symbol="e-interactionCreate" /> in your _`index.js`_ file.
You should first check if an interaction is a chat input command via <DocsLink type="class" parent="BaseInteraction" symbol="isChatInputCommand" brackets>_`.isChatInputCommand()`_</DocsLink>, and then check the <DocsLink type="class" parent="CommandInteraction" symbol="commandName">_`.commandName`_</DocsLink> property to know which command it is. You can respond to interactions with <DocsLink type="class" parent="CommandInteraction" symbol="reply" brackets>_`.reply()`_</DocsLink>.
<CH.Code>
```js mark=5:16
client.once('ready', () => {
console.log('Ready!');
});
client.on('interactionCreate', async (interaction) => {
if (!interaction.isChatInputCommand()) return;
const { commandName } = interaction;
if (commandName === 'ping') {
await interaction.reply('Pong!');
} else if (commandName === 'server') {
await interaction.reply('Server info.');
} else if (commandName === 'user') {
await interaction.reply('User info.');
}
});
client.login(token);
```
</CH.Code>
### Server info command
Note that servers are referred to as "guilds" in the Discord API and discord.js library. _`interaction.guild`_ refers to the guild the interaction was sent in (a <DocsLink type="class" parent="Guild" /> instance), which exposes properties such as _`.name`_ or _`.memberCount`_.
<CH.Code>
```js focus=7
client.on('interactionCreate', async (interaction) => {
if (!interaction.isChatInputCommand()) return;
const { commandName } = interaction;
if (commandName === 'ping') {
await interaction.reply('Pong!');
} else if (commandName === 'server') {
await interaction.reply(`Server name: ${interaction.guild.name}\nTotal members: ${interaction.guild.memberCount}`);
} else if (commandName === 'user') {
await interaction.reply('User info.');
}
});
```
</CH.Code>
<DiscordMessages rounded>
<DiscordMessage
interaction={{
author: {
avatar:
'https://cdn.discordapp.com/guilds/222078108977594368/users/81440962496172032/avatars/c059c5d04d717ea05790f7a6447e4843.webp?size=160',
username: 'Crawl',
},
command: 'server',
}}
author={{
avatar:
'https://cdn.discordapp.com/guilds/222078108977594368/users/81440962496172032/avatars/c059c5d04d717ea05790f7a6447e4843.webp?size=160',
username: 'Crawl',
time: 'Today at 21:00',
}}
>
<p>Server name: discord.js Guide</p>
<p>Total members: 2</p>
</DiscordMessage>
</DiscordMessages>
You could also display the date the server was created, or the server's verification level. You would do those in the same manner use _`interaction.guild.createdAt`_ or _`interaction.guild.verificationLevel`_, respectively.
<Alert title="Tip" type="success">
Refer to the <DocsLink type="class" parent="Guild" /> documentation for a list of all the available properties and
methods!
</Alert>
### User info command
A "user" refers to a Discord user. _`interaction.user`_ refers to the user the interaction was sent by (a <DocsLink type="class" parent="User" /> instance), which exposes properties such as _`.tag`_ or _`.id`_.
<CH.Code>
```js focus=9
client.on('interactionCreate', async (interaction) => {
if (!interaction.isChatInputCommand()) return;
const { commandName } = interaction;
if (commandName === 'ping') {
await interaction.reply('Pong!');
} else if (commandName === 'server') {
await interaction.reply(`Server name: ${interaction.guild.name}\nTotal members: ${interaction.guild.memberCount}`);
} else if (commandName === 'user') {
await interaction.reply(`Your tag: ${interaction.user.tag}\nYour id: ${interaction.user.id}`);
}
});
```
</CH.Code>
<DiscordMessages rounded>
<DiscordMessage
interaction={{
author: {
avatar:
'https://cdn.discordapp.com/guilds/222078108977594368/users/81440962496172032/avatars/c059c5d04d717ea05790f7a6447e4843.webp?size=160',
username: 'Crawl',
},
command: 'user',
}}
author={{
avatar:
'https://cdn.discordapp.com/guilds/222078108977594368/users/81440962496172032/avatars/c059c5d04d717ea05790f7a6447e4843.webp?size=160',
username: 'Crawl',
time: 'Today at 21:00',
}}
>
<p>Your tag: User#0001</p>
<p>Your id: 123456789012345678</p>
</DiscordMessage>
</DiscordMessages>
<Alert title="Tip" type="success">
Refer to the <DocsLink type="class" parent="User" /> documentation for a list of all the available properties and
methods!
</Alert>
And there you have it!
## The problem with if/else if
If you don't plan on making more than a couple commands, then using an _`if`_/_`else if`_ chain is fine; however, this isn't always the case. Using a giant _`if`_/_`else if`_ chain will only hinder your development process in the long run.
Here's a small list of reasons why you shouldn't do so:
- Takes longer to find a piece of code you want;
- Easier to fall victim to [spaghetti code](https://en.wikipedia.org/wiki/Spaghetti_code);
- Difficult to maintain as it grows;
- Difficult to debug;
- Difficult to organize;
- General bad practice.
Next, we'll be diving into something called a "command handler" code that makes handling commands easier and much more efficient. This allows you to move your commands into individual files.
## Resulting code
<ResultingCode />

View File

@@ -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 questionsyou 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.

View File

@@ -0,0 +1,6 @@
---
title: Setting up a linter
category: Installations and preparations
---
TODO: Rewrite. Placeholder page for ordering.

View File

@@ -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:
![Successfully created application](/assets/create-app.png)
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:
![Bot application](/assets/bot-user.png)
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>

View File

@@ -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):
![Bot Authorization page](/assets/bot-auth-page.png)
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:
![Bot authorized](/assets/bot-authorized.png)
Congratulations! You've successfully added your bot to your Discord server. It should show up in your server's member list somewhat like this:
![Bot in server's member list](/assets/bot-in-memberlist.png)

View File

@@ -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>

View File

@@ -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" />

View File

@@ -0,0 +1,147 @@
---
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
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
export async function execute(interaction) {
await interaction.reply('Pong!');
}
```
</CH.Code>
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
export const data = {
name: 'ping',
description: 'Replies with Pong!',
};
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
export const data = {
name: 'user',
description: 'Provides information about the user.',
};
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
export const data = {
name: 'server',
description: 'Provides information about the server.',
};
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 />

View File

@@ -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:
![Project structure before sorting](/assets/before-sorting.png)
After moving your commands into subfolders, it will look something like this:
![Project structure after sorting](/assets/after-sorting.png)
<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!

View File

@@ -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" />

View File

@@ -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 />

View File

@@ -0,0 +1,496 @@
---
title: Frequently asked questions
category: Popular topics
---
# Frequently asked questions
## Legend
- _`client`_ is a placeholder for the <DocsLink type="class" parent="Client" /> object:
_`const client = new Client({ intents: [GatewayIntentBits.Guilds] });`_.
- _`interaction`_ is a placeholder for the <DocsLink type="class" parent="BaseInteraction" />:
_`client.on(Events.InteractionCreate, interaction => { ... });`_.
- _`guild`_ is a placeholder for the <DocsLink type="class" parent="Guild" /> object:
_`interaction.guild`_ or _`client.guilds.cache.get('id')`_
- _`voiceChannel`_ is a placeholder for the <DocsLink type="class" parent="VoiceChannel" />:
_`interaction.member.voice.channel`_.
For a more detailed explanation of the notations commonly used in this guide, the docs, and the support server, see [here](/additional-info/notation.md).
## Administrative
### How do I ban a user?
<CH.Code>
```js
const user = interaction.options.getUser('target');
await guild.members.ban(user);
```
</CH.Code>
### How do I unban a user?
<CH.Code>
```js
const user = interaction.options.getUser('target');
await guild.members.unban(user);
```
</CH.Code>
<Alert title="Tip" type="info">
Discord validates and resolves user ids for users not on the server in user slash command options. To retrieve and use
the full structure from the resulting interaction, you can use the{' '}
<DocsLink type="class" parent="CommandInteractionOptionResolver" symbol="getUser" brackets /> method.
</Alert>
### How do I kick a guild member?
<CH.Code>
```js
const member = interaction.options.getMember('target');
await member.kick();
```
</CH.Code>
### How do I timeout a guild member?
<CH.Code>
```js
const member = interaction.options.getMember('target');
await member.timeout(60_000); // Timeout for one minute
```
</CH.Code>
<Alert title="Tip" type="info">
Timeout durations are measured by the millisecond. The maximum timeout duration you can set is 28 days. To remove a
timeout set on a member, pass _`null`_ instead of a timeout duration.
</Alert>
### How do I add a role to a guild member?
<CH.Code>
```js
const role = interaction.options.getRole('role');
const member = interaction.options.getMember('target');
await member.roles.add(role);
```
</CH.Code>
### How do I check if a guild member has a specific role?
<CH.Code>
```js
const role = interaction.options.getRole('role');
const member = interaction.options.getMember('target');
if (member.roles.cache.has(role.id) {
// ...
}
```
</CH.Code>
### How do I limit a command to a single user?
<CH.Code>
```js
if (interaction.user.id === 'id') {
// ...
}
```
</CH.Code>
## Bot Configuration and Utility
### How do I set my bot's username?
<CH.Code>
```js
await client.user.setUsername('username');
```
</CH.Code>
### How do I set my bot's avatar?
<CH.Code>
```js
await client.user.setAvatar('URL or path');
```
</CH.Code>
### How do I set my playing status?
<CH.Code>
```js
client.user.setActivity('activity');
```
</CH.Code>
### How do I set my status to "Watching/Listening to/Competing in ..."?
<CH.Code>
```js
import { ActivityType } from 'discord.js';
client.user.setActivity('activity', { type: ActivityType.Watching });
client.user.setActivity('activity', { type: ActivityType.Listening });
client.user.setActivity('activity', { type: ActivityType.Competing });
```
</CH.Code>
<Alert title="Tip" type="info">
If you would like to set your activity upon startup, you can use the{' '}
<DocsLink type="typedef" parent="ClientOptions" /> object to set the appropriate
<DocsLink type="typedef" parent="PresenceData" />.
</Alert>
### How do I make my bot display online/idle/dnd/invisible?
<CH.Code>
```js
client.user.setStatus('online');
client.user.setStatus('idle');
client.user.setStatus('dnd');
client.user.setStatus('invisible');
```
</CH.Code>
### How do I set both status and activity in one go?
<CH.Code>
```js
client.user.setPresence({ activities: [{ name: 'activity' }], status: 'idle' });
```
</CH.Code>
## Miscellaneous
### How do I send a message to a specific channel?
<CH.Code>
```js
const channel = client.channels.cache.get('id');
await channel.send('content');
```
</CH.Code>
### How do I create a post in a forum channel?
<Alert title="Tip" type="info">
Currently, the only way to get tag ids is programmatically through{' '}
<DocsLink type="class" parent="ForumChannel" symbol="availableTags" />.
</Alert>
<CH.Code>
```js
const channel = client.channels.cache.get('id');
await channel.threads.create({
name: 'Post name',
message: { content: 'Message content' },
appliedTags: ['tagId', 'anotherTagId'],
});
```
</CH.Code>
### How do I DM a specific user?
<CH.Code>
```js
await client.users.send('id', 'content');
```
</CH.Code>
<Alert title="Tip" type="info">
If you want to send a direct message to the user who sent the interaction, you can use _`interaction.user.send()`_.
</Alert>
### How do I mention a specific user in a message?
<CH.Code>
```js
const user = interaction.options.getUser('target');
await interaction.reply(`Hi, ${user}.`);
await interaction.followUp(`Hi, <@${user.id}>.`);
```
</CH.Code>
<Alert title="Tip" type="info">
Mentions in embeds may resolve correctly in embed titles, descriptions and field values but will never notify the
user. Other areas do not support mentions at all.
</Alert>
### How do I control which users and/or roles are mentioned in a message?
Controlling which mentions will send a ping is done via the _`allowedMentions`_ option, which replaces _`disableMentions`_.
This can be set as a default in <DocsLink type="typedef" parent="ClientOptions" />, and controlled per-message sent by your bot.
<CH.Code>
```js
new Client({ allowedMentions: { parse: ['users', 'roles'] } });
```
</CH.Code>
Even more control can be achieved by listing specific _`users`_ or _`roles`_ to be mentioned by id, e.g.:
<CH.Code>
```js
await channel.send({
content: '<@123456789012345678> <@987654321098765432> <@&102938475665748392>',
allowedMentions: { users: ['123456789012345678'], roles: ['102938475665748392'] },
});
```
</CH.Code>
### How do I prompt the user for additional input?
<CH.Code>
```js
await interaction.reply('Please enter more input.');
const filter = (m) => interaction.user.id === m.author.id;
try {
const messages = await interaction.channel.awaitMessages({ filter, time: 60000, max: 1, errors: ['time'] });
await interaction.followUp(`You've entered: ${messages.first().content}`);
} catch {
await interaction.followUp('You did not enter any input!');
}
```
</CH.Code>
<Alert title="Tip" type="info">
If you want to learn more about this syntax or other types of collectors, check out [this dedicated guide page for
collectors](/popular-topics/collectors.md)!
</Alert>
### How do I block a user from using my bot?
<CH.Code>
```js
const blockedUsers = ['id1', 'id2'];
client.on(Events.InteractionCreate, (interaction) => {
if (blockedUsers.includes(interaction.user.id)) return;
});
```
</CH.Code>
<Alert title="Tip" type="info">
You do not need to have a constant local variable like _`blockedUsers`_ above. If you have a database system that you
use to store ids of blocked users, you can query the database instead.
</Alert>
<CH.Code>
```js
client.on(Events.InteractionCreate, async (interaction) => {
const blockedUsers = await database.query('SELECT user_id FROM blocked_users;');
if (blockedUsers.includes(interaction.user.id)) return;
});
```
</CH.Code>
Note that this is just a showcase of how you could do such a check.
### How do I react to the message my bot sent?
<CH.Code>
```js
const sentMessage = await interaction.channel.send('My message to react to.');
// Unicode emoji
await sentMessage.react('👍');
// Custom emoji
await sentMessage.react('123456789012345678');
await sentMessage.react('<emoji:123456789012345678>');
await sentMessage.react('<a:emoji:123456789012345678>');
await sentMessage.react('emoji:123456789012345678');
await sentMessage.react('a:emoji:123456789012345678');
```
</CH.Code>
<Alert title="Tip" type="info">
If you want to learn more about reactions, check out [this dedicated guide on
reactions](/popular-topics/reactions.md)!
</Alert>
### How do I restart my bot with a command?
<CH.Code>
```js
process.exit();
```
</CH.Code>
<Alert title="Warning" type="warning">
_`process.exit()`_ will only kill your Node process, but when using [PM2](https://pm2.keymetrics.io/), it will restart
the process whenever it gets killed. You can read our guide on PM2 [here](/improving-dev-environment/pm2.md).
</Alert>
### What is the difference between a User and a GuildMember?
A User represents a global Discord user, and a GuildMember represents a Discord user on a specific server. That means only GuildMembers can have permissions, roles, and nicknames, for example, because all of these things are server-bound information that could be different on each server that the user is in.
### How do I find all online members of a guild?
<CH.Code>
```js
// First use guild.members.fetch to make sure all members are cached
const fetchedMembers = await guild.members.fetch({ withPresences: true });
const totalOnline = fetchedMembers.filter((member) => member.presence?.status === 'online');
// Now you have a collection with all online member objects in the totalOnline variable
console.log(`There are currently ${totalOnline.size} members online in this guild!`);
```
</CH.Code>
<Alert title="Warning" type="warning">
This only works correctly if you have the _`GuildPresences`_ intent enabled for your application and client. If you
want to learn more about intents, check out [this dedicated guide on intents](/popular-topics/intents.md)!
</Alert>
### How do I check which role was added/removed and for which member?
<CH.Code>
```js
// Start by declaring a guildMemberUpdate listener
// This code should be placed outside of any other listener callbacks to prevent listener nesting
client.on(Events.GuildMemberUpdate, (oldMember, newMember) => {
// If the role(s) are present on the old member object but no longer on the new one (i.e role(s) were removed)
const removedRoles = oldMember.roles.cache.filter((role) => !newMember.roles.cache.has(role.id));
if (removedRoles.size > 0) {
console.log(`The roles ${removedRoles.map((r) => r.name)} were removed from ${oldMember.displayName}.`);
}
// If the role(s) are present on the new member object but are not on the old one (i.e role(s) were added)
const addedRoles = newMember.roles.cache.filter((role) => !oldMember.roles.cache.has(role.id));
if (addedRoles.size > 0) {
console.log(`The roles ${addedRoles.map((r) => r.name)} were added to ${oldMember.displayName}.`);
}
});
```
</CH.Code>
### How do I check the bot's ping?
There are two common measurements for bot pings. The first, **websocket heartbeat**, is the average interval of a regularly sent signal indicating the healthy operation of the websocket connection the library receives events over:
<CH.Code>
```js
await interaction.reply(`Websocket heartbeat: ${client.ws.ping}ms.`);
```
</CH.Code>
<Alert title="Tip" type="info">
If you're using [sharding](/sharding/), a specific shard's heartbeat can be found on the WebSocketShard instance,
accessible at _`client.ws.shards.get(id).ping`_.
</Alert>
The second, **Roundtrip Latency**, describes the amount of time a full API roundtrip (from the creation of the command message to the creation of the response message) takes. You then edit the response to the respective value to avoid needing to send yet another message:
<CH.Code>
```js
const sent = await interaction.reply({ content: 'Pinging...', fetchReply: true });
await interaction.editReply(`Roundtrip latency: ${sent.createdTimestamp - interaction.createdTimestamp}ms`);
```
</CH.Code>
### Why do some emojis behave weirdly?
If you've tried using [the usual method of retrieving unicode emojis](./reactions.md#unicode-emojis), you may have noticed that some characters don't provide the expected results. Here's a short snippet that'll help with that issue. You can toss this into a file of its own and use it anywhere you need! Alternatively feel free to simply copy-paste the characters from below:
<CH.Code>
```js index.js
import { emojiCharacters } from './emojiCharacters.js';
console.log(emojiCharacters.a); // 🇦
console.log(emojiCharacters[10]); // 🔟
console.log(emojiCharacters['!']); // ❗
```
{/* prettier-ignore */}
```js emojiCharacters.js
export const emojiCharacters = {
a: '🇦', b: '🇧', c: '🇨', d: '🇩',
e: '🇪', f: '🇫', g: '🇬', h: '🇭',
i: '🇮', j: '🇯', k: '🇰', l: '🇱',
m: '🇲', n: '🇳', o: '🇴', p: '🇵',
q: '🇶', r: '🇷', s: '🇸', t: '🇹',
u: '🇺', v: '🇻', w: '🇼', x: '🇽',
y: '🇾', z: '🇿', 0: '0⃣', 1: '1⃣',
2: '2⃣', 3: '3⃣', 4: '4⃣', 5: '5⃣',
6: '6⃣', 7: '7⃣', 8: '8⃣', 9: '9⃣',
10: '🔟', '#': '#️⃣', '*': '*️⃣',
'!': '❗', '?': '❓',
};
```
</CH.Code>
<Alert title="Tip" type="info">
You can use the <kbd>⌃ Control</kbd> <kbd>⌘ Command</kbd> <kbd>Space</kbd> keyboard shortcut to open up an emoji picker that can be used for quick, easy access to all the Unicode emojis available to you.
On Windows, the shortcut is <kbd>⊞</kbd> <kbd>.</kbd>.
</Alert>

View File

@@ -0,0 +1,165 @@
---
title: Audit logs
category: Popular topics
---
# Audit logs
## A Quick Background
Audit logs are an excellent moderation tool offered by Discord to know what happened in a server and usually by whom. Making use of audit logs requires the _`ViewAuditLog`_ permission. Audit logs may be fetched on a server, or they may be received via the gateway event <DocsLink type="class" parent="Client" symbol="e-guildAuditLogEntryCreate"/> which requires the _`GuildModeration`_ intent.
There are quite a few cases where you may use audit logs. This guide will limit itself to the most common use cases. Feel free to consult the [relevant Discord API page](https://discord.com/developers/docs/resources/audit-log) for more information.
Keep in mind that these examples explore a straightforward case and are by no means exhaustive. Their purpose is to teach you how audit logs work, and expansion of these examples is likely needed to suit your specific use case.
## Fetching Audit Logs
Let's start by glancing at the <DocsLink type="class" parent="Guild" symbol="fetchAuditLogs" brackets /> method and how to work with it. Like many discord.js methods, it returns a [Promise](../additional-info/understanding-async-await) containing the <DocsLink type="class" parent="GuildAuditLogs"/> object. This object has one property, _`entries`_, which holds a [Collection](../additional-info/collections) of <DocsLink type="class" parent="GuildAuditLogsEntry"/> objects, and consequently, the information you want to retrieve.
Here is the most basic fetch to look at some entries.
<CH.Code>
```js
const fetchedLogs = await guild.fetchAuditLogs();
const firstEntry = fetchedLogs.entries.first();
```
</CH.Code>
Simple, right? Now, let's look at utilizing its options:
<CH.Code>
```js
import { AuditLogEvent } from 'discord.js';
const fetchedLogs = await guild.fetchAuditLogs({
type: AuditLogEvent.InviteCreate,
limit: 1,
});
const firstEntry = fetchedLogs.entries.first();
```
</CH.Code>
This will return the first entry where an invite was created. You used _`limit: 1`_ here to specify only one entry.
## Receiving Audit Logs
Audit logs may be received via the gateway event <DocsLink type="class" parent="Client" symbol="e-guildAuditLogEntryCreate"/>.
This is the best way to receive audit logs if you want to monitor them. As soon as an audit log entry is created,
your application will receive an instance of this event. A common use case is to find out _who_ did the action that
caused the audit log event to happen.
### Who deleted a message?
One of the most common use cases for audit logs is understanding who deleted a message in a Discord server. If a user deleted another user's message, you can find out who did that as soon as you receive the corresponding audit log event.
<Alert title="Tip" type="info">
Messages deleted by their author or bots (excluding bulk deletes) do not generate audit log entries.
</Alert>
<CH.Code>
```js JavaScript
import { AuditLogEvent, Events } from 'discord.js';
client.on(Events.GuildAuditLogEntryCreate, async (auditLog) => {
// Define your variables.
// The extra information here will be the channel.
const { action, extra: channel, executorId, targetId } = auditLog;
// Check only for deleted messages.
if (action !== AuditLogEvent.MessageDelete) return;
// Ensure the executor is cached.
const executor = await client.users.fetch(executorId);
// Ensure the author whose message was deleted is cached.
const target = await client.users.fetch(targetId);
// Log the output.
console.log(`A message by ${target.tag} was deleted by ${executor.tag} in ${channel}.`);
});
```
```ts TypeScript
import { AuditLogEvent, Events } from 'discord.js';
client.on(Events.GuildAuditLogEntryCreate, async (auditLog) => {
// Define your variables.
// The extra information here will be the channel.
const { action, extra: channel, executorId, targetId } = auditLog;
// Check only for deleted messages.
if (action !== AuditLogEvent.MessageDelete) return;
// Ensure the executor is cached. The id definitely exists.
const executor = await client.users.fetch(executorId!);
// Ensure the author whose message was deleted is cached. The id definitely exists.
const target = await client.users.fetch(targetId!);
// Log the output.
console.log(`A message by ${target.tag} was deleted by ${executor.tag} in ${channel}.`);
});
```
</CH.Code>
With this, you now have a very simple logger telling you who deleted a message authored by another person.
### Who kicked a user?
This is very similar to the example above.
<CH.Code>
```js JavaScript
import { AuditLogEvent, Events } from 'discord.js';
client.on(Events.GuildAuditLogEntryCreate, async (auditLog) => {
// Define your variables.
const { action, executorId, targetId } = auditLog;
// Check only for kicked users.
if (action !== AuditLogEvent.MemberKick) return;
// Ensure the executor is cached.
const executor = await client.users.fetch(executorId);
// Ensure the kicked guild member is cached.
const kickedUser = await client.users.fetch(targetId);
// Now you can log the output!
console.log(`${kickedUser.tag} was kicked by ${executor.tag}.`);
});
```
```ts TypeScript
import { AuditLogEvent, Events } from 'discord.js';
client.on(Events.GuildAuditLogEntryCreate, async (auditLog) => {
// Define your variables.
const { action, executorId, targetId } = auditLog;
// Check only for kicked users.
if (action !== AuditLogEvent.MemberKick) return;
// Ensure the executor is cached. The id definitely exists.
const executor = await client.users.fetch(executorId!);
// Ensure the kicked guild member is cached. The id definitely exists.
const kickedUser = await client.users.fetch(targetId!);
// Now you can log the output!
console.log(`${kickedUser.tag} was kicked by ${executor.tag}.`);
});
```
</CH.Code>
If you want to check who banned a user, it's the same example as above except the _`action`_ should be _`AuditLogEvent.MemberBanAdd`_. You can check the rest of the types over at the [discord-api-types documentation](https://discord-api-types.dev/api/discord-api-types-v10/enum/AuditLogEvent).

View File

@@ -0,0 +1,202 @@
---
title: Threads
category: Popular topics
---
# Threads
Threads can be thought of as temporary sub-channels inside an existing channel to help better organize conversations in a busy channel.
## Thread related gateway events
<Alert title="Tip" type="info">
You can use the <DocsLink type="class" parent="BaseChannel" symbol="isThread" brackets /> type guard to make sure a
channel is a <DocsLink type="class" parent="ThreadChannel" />!
</Alert>
Threads introduce a number of new gateway events, which are listed below:
- <DocsLink type="class" parent="Client" symbol="e-threadCreate" />: Emitted whenever a thread is created or when the
client user is added to a thread.
- <DocsLink type="class" parent="Client" symbol="e-threadDelete" />: Emitted whenever a thread is deleted.
- <DocsLink type="class" parent="Client" symbol="e-threadUpdate" />: Emitted whenever a thread is updated (e.g. name
change, archive state change, locked state change).
- <DocsLink type="class" parent="Client" symbol="e-threadListSync" />: Emitted whenever the client user gains access to
a text or announcement channel that contains threads.
- <DocsLink type="class" parent="Client" symbol="e-threadMembersUpdate" />: Emitted whenever members are added or
removed from a thread. Requires <code>GuildMembers</code> privileged intent.
- <DocsLink type="class" parent="Client" symbol="e-threadMemberUpdate" />: Emitted whenever the client user's thread
member is updated.
## Creating and deleting threads
Threads are created and deleted using the <DocsLink type="class" parent="GuildTextThreadManager" /> of a text or announcement channel.
To create a thread, you call the <DocsLink type="class" parent="GuildTextThreadManager" symbol="create" brackets /> method:
<CH.Code>
```js
import { ThreadAutoArchiveDuration } from 'discord.js';
const thread = await channel.threads.create({
name: 'food-talk',
autoArchiveDuration: ThreadAutoArchiveDuration.OneHour,
reason: 'Needed a separate thread for food',
});
console.log(`Created thread: ${thread.name}`);
```
</CH.Code>
They can also be created from an existing message with the <DocsLink type="class" parent="Message" symbol="startThread" brackets /> method, but will be "orphaned" if that message is deleted.
<CH.Code>
```js focus=3[22:42]
import { ThreadAutoArchiveDuration } from 'discord.js';
const thread = await message.startThread({
name: 'food-talk',
autoArchiveDuration: ThreadAutoArchiveDuration.OneHour,
reason: 'Needed a separate thread for food',
});
console.log(`Created thread: ${thread.name}`);
```
</CH.Code>
The created thread and the message it originated from will share the same id. The type of thread created matches the parent channel's type.
To delete a thread, use the <DocsLink type="class" parent="ThreadChannel" symbol="delete" brackets /> method:
<CH.Code>
```js focus=2
const thread = channel.threads.cache.find((x) => x.name === 'food-talk');
if (thread.manageable) await thread.delete();
```
</CH.Code>
## Joining and leaving threads
To subscribe your client to a thread, use the <DocsLink type="class" parent="ThreadChannel" symbol="join" brackets /> method:
<CH.Code>
```js focus=2
const thread = channel.threads.cache.find((x) => x.name === 'food-talk');
if (thread.joinable) await thread.join();
```
</CH.Code>
And to leave one, use the <DocsLink type="class" parent="ThreadChannel" symbol="leave" brackets /> method:
<CH.Code>
```js focus=2
const thread = channel.threads.cache.find((x) => x.name === 'food-talk');
await thread.leave();
```
</CH.Code>
## Archiving, unarchiving, and locking threads
A thread can be either active or archived. Changing a thread from archived to active is referred to as unarchiving the thread. Threads that have _`locked`_ set to _`true`_ can only be unarchived by a member with the _`ManageThreads`_ permission.
Threads are automatically archived after inactivity. "Activity" is defined as sending a message, unarchiving a thread, or changing the auto-archive time.
To archive or unarchive a thread, use the <DocsLink type="class" parent="ThreadChannel" symbol="setArchived" brackets /> method and pass in a boolean parameter:
<CH.Code>
```js focus=2,3
const thread = channel.threads.cache.find((x) => x.name === 'food-talk');
await thread.setArchived(true); // Archived.
await thread.setArchived(false); // Unarchived.
```
</CH.Code>
This same principle applies to locking and unlocking a thread via the <DocsLink type="class" parent="ThreadChannel" symbol="setLocked" brackets /> method:
<CH.Code>
```js focus=2,3
const thread = channel.threads.cache.find((x) => x.name === 'food-talk');
await thread.setLocked(true); // Locked.
await thread.setLocked(false); // Unlocked.
```
</CH.Code>
## Private threads
Public threads are viewable by everyone who can view the parent channel of the thread. Private threads, however, are only viewable to those who are invited or have the _`ManageThreads`_ permission. Private threads can only be created on text channels.
To create a private thread, use the <DocsLink type="class" parent="GuildTextThreadManager" symbol="create" brackets /> method and pass in _`ChannelType.PrivateThread`_ as the _`type`_:
<CH.Code>
```js focus=1[10:21],6
import { ChannelType, ThreadAutoArchiveDuration } from 'discord.js';
const thread = await channel.threads.create({
name: 'mod-talk',
autoArchiveDuration: ThreadAutoArchiveDuration.OneHour,
type: ChannelType.PrivateThread,
reason: 'Needed a separate thread for moderation',
});
console.log(`Created thread: ${thread.name}`);
```
</CH.Code>
## Adding and removing members
You can add members to a thread with the <DocsLink type="class" parent="ThreadMemberManager" symbol="add" brackets /> method. The thread must be unarchived and you must be able to send messages in it.
<CH.Code>
```js focus=2
const thread = channel.threads.cache.find((x) => x.name === 'food-talk');
await thread.members.add('12345678901234567');
```
</CH.Code>
You can remove members from a thread with the <DocsLink type="class" parent="ThreadMemberManager" symbol="remove" brackets /> method. The thread must be unarchived and you must have the _`ManageThreads`_ permission unless the thread is private and you are the owner of it.
<CH.Code>
```js focus=2
const thread = channel.threads.cache.find((x) => x.name === 'food-talk');
await thread.members.remove('12345678901234567');
```
</CH.Code>
## Sending messages to threads with webhooks
It is possible for a webhook built on the parent channel to send messages to the channel's threads. For the purpose of this example, it is assumed a single webhook already exists for that channel. If you wish to learn more about webhooks, see our [webhook guide](./webhooks).
<CH.Code>
```js focus=4:7
const webhooks = await channel.fetchWebhooks();
const webhook = webhooks.first();
await webhook.send({
content: "Look ma! I'm in a thread!",
threadId: '123456789012345678',
});
```
</CH.Code>
And that's it! Now you know all there is to know on working with threads using discord.js!

View File

@@ -419,7 +419,7 @@ The base interaction class is now <DocsLink type="class" parent="BaseInteraction
### MessageManager
The second paramter of <DocsLink type="class" parent="MessageManager" symbol="fetch" brackets /> has been removed. The <DocsLink type="class" parent="BaseFetchOptions" /> the second parameter once was is now merged into the first parameter.
The second parameter of <DocsLink type="class" parent="MessageManager" symbol="fetch" brackets /> has been removed. The <DocsLink type="class" parent="BaseFetchOptions" /> the second parameter once was is now merged into the first parameter.
<CH.Code>

View File

@@ -19,7 +19,8 @@
"~/*": ["./src/*"],
"contentlayer/generated": ["./.contentlayer/generated"]
},
"strictNullChecks": true
"strictNullChecks": true,
"moduleResolution": "node"
},
"include": [
"src/**/*.ts",

View File

@@ -38,7 +38,8 @@
],
"repository": {
"type": "git",
"url": "https://github.com/discordjs/discord.js.git"
"url": "https://github.com/discordjs/discord.js.git",
"directory": "apps/website"
},
"bugs": {
"url": "https://github.com/discordjs/discord.js/issues"
@@ -48,19 +49,20 @@
"@discordjs/api-extractor-utils": "workspace:^",
"@discordjs/scripts": "workspace:^",
"@discordjs/ui": "workspace:^",
"@microsoft/api-extractor-model": "7.26.4",
"@microsoft/api-extractor-model": "7.26.6",
"@microsoft/tsdoc": "0.14.2",
"@planetscale/database": "1.7.0",
"@react-icons/all-files": "^4.1.0",
"@vercel/analytics": "^0.1.11",
"@vercel/edge-config": "^0.1.7",
"@vercel/og": "^0.5.2",
"@vercel/analytics": "^1.0.0",
"@vercel/edge-config": "^0.1.8",
"@vercel/og": "^0.5.4",
"@vscode/codicons": "^0.0.32",
"ariakit": "^2.0.0-next.44",
"bright": "^0.7.1",
"bright": "^0.8.2",
"class-variance-authority": "^0.6.0",
"cmdk": "^0.2.0",
"meilisearch": "^0.32.3",
"next": "^13.3.1-canary.8",
"next": "^13.3.4",
"next-mdx-remote": "^4.4.1",
"next-themes": "^0.2.1",
"react": "^18.2.0",
@@ -72,33 +74,33 @@
"rehype-slug": "^5.1.0",
"remark-gfm": "^3.0.1",
"server-only": "^0.0.1",
"sharp": "^0.32.0",
"swr": "^2.1.3"
"sharp": "^0.32.1",
"swr": "^2.1.5"
},
"devDependencies": {
"@next/bundle-analyzer": "^13.3.0",
"@next/bundle-analyzer": "^13.3.4",
"@testing-library/react": "^14.0.0",
"@testing-library/user-event": "^14.4.3",
"@types/node": "18.15.11",
"@types/react": "^18.0.35",
"@types/react-dom": "^18.0.11",
"@unocss/cli": "^0.51.4",
"@unocss/eslint-config": "^0.51.4",
"@unocss/reset": "^0.51.4",
"@vitejs/plugin-react": "^3.1.0",
"@types/node": "18.16.3",
"@types/react": "^18.2.0",
"@types/react-dom": "^18.2.1",
"@unocss/cli": "^0.51.8",
"@unocss/eslint-config": "^0.51.8",
"@unocss/reset": "^0.51.8",
"@vitejs/plugin-react": "^4.0.0",
"@vitest/coverage-c8": "^0.30.1",
"concurrently": "^8.0.1",
"cpy-cli": "^4.2.0",
"cross-env": "^7.0.3",
"eslint": "^8.38.0",
"eslint": "^8.39.0",
"eslint-config-neon": "^0.1.42",
"eslint-formatter-pretty": "^5.0.0",
"happy-dom": "^9.7.1",
"happy-dom": "^9.10.1",
"lighthouse": "^10.1.1",
"prettier": "^2.8.7",
"prettier": "^2.8.8",
"typescript": "^5.0.4",
"unocss": "^0.51.4",
"vercel": "^28.18.5",
"unocss": "^0.51.8",
"vercel": "^29.0.3",
"vitest": "^0.29.8"
},
"engines": {

View File

@@ -3,6 +3,7 @@ import { VscArrowRight } from '@react-icons/all-files/vsc/VscArrowRight';
import { VscVersions } from '@react-icons/all-files/vsc/VscVersions';
import Link from 'next/link';
import { notFound } from 'next/navigation';
import { buttonVariants } from '~/styles/Button';
import { PACKAGES } from '~/util/constants';
export const runtime = 'edge';
@@ -31,7 +32,7 @@ export default async function Page({ params }: { params: { package: string } })
<div className="flex flex-col gap-4">
{data.map((version, idx) => (
<Link
className="h-11 flex flex-col transform-gpu cursor-pointer select-none appearance-none place-content-center border border-neutral-300 rounded bg-white p-4 text-base font-semibold leading-none text-black outline-none active:translate-y-px dark:border-dark-100 active:bg-neutral-200 dark:bg-dark-400 hover:bg-neutral-100 dark:text-white focus:ring focus:ring-width-2 focus:ring-blurple dark:active:bg-dark-200 dark:hover:bg-dark-300"
className={buttonVariants({ variant: 'secondary' })}
href={`/docs/packages/${params.package}/${version}`}
key={`${version}-${idx}`}
>
@@ -45,10 +46,7 @@ export default async function Page({ params }: { params: { package: string } })
</Link>
)) ?? null}
</div>
<Link
className="h-11 flex flex-row transform-gpu cursor-pointer select-none appearance-none place-items-center place-self-center gap-2 border-0 rounded bg-blurple px-4 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="/docs/packages"
>
<Link className={buttonVariants({ className: 'place-self-center' })} href="/docs/packages">
<VscArrowLeft size={20} /> Go back
</Link>
</div>

View File

@@ -3,6 +3,7 @@ import { VscArrowLeft } from '@react-icons/all-files/vsc/VscArrowLeft';
import { VscArrowRight } from '@react-icons/all-files/vsc/VscArrowRight';
import { VscPackage } from '@react-icons/all-files/vsc/VscPackage';
import Link from 'next/link';
import { buttonVariants } from '~/styles/Button';
import { PACKAGES } from '~/util/constants';
export const runtime = 'edge';
@@ -28,7 +29,7 @@ export default function Page() {
</a>
{PACKAGES.map((pkg, idx) => (
<Link
className="h-11 flex flex-row transform-gpu cursor-pointer select-none appearance-none place-content-between border border-neutral-300 rounded bg-white p-4 text-base font-semibold leading-none text-black outline-none active:translate-y-px dark:border-dark-100 active:bg-neutral-200 dark:bg-dark-400 hover:bg-neutral-100 dark:text-white focus:ring focus:ring-width-2 focus:ring-blurple dark:active:bg-dark-200 dark:hover:bg-dark-300"
className={buttonVariants({ variant: 'secondary' })}
href={`/docs/packages/${pkg}`}
key={`${pkg}-${idx}`}
>
@@ -51,10 +52,7 @@ export default function Page() {
</div>
</Link>
))}
<a
className="h-11 flex transform-gpu cursor-pointer select-none appearance-none place-content-between border border-neutral-300 rounded bg-white p-4 text-base font-semibold leading-none text-black outline-none active:translate-y-px dark:border-dark-100 active:bg-neutral-200 dark:bg-dark-400 hover:bg-neutral-100 dark:text-white focus:ring focus:ring-width-2 focus:ring-blurple dark:active:bg-dark-200 dark:hover:bg-dark-300"
href="https://discord-api-types.dev/"
>
<a className={buttonVariants({ variant: 'secondary' })} href="https://discord-api-types.dev/">
<div className="flex grow flex-row place-content-between place-items-center gap-4">
<div className="flex grow flex-row place-content-between place-items-center gap-4">
<div className="flex flex-row place-content-between place-items-center gap-4">
@@ -66,10 +64,7 @@ export default function Page() {
</div>
</a>
</div>
<Link
className="h-11 flex flex-row transform-gpu cursor-pointer select-none appearance-none place-items-center place-self-center gap-2 border-0 rounded bg-blurple px-4 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="/"
>
<Link className={buttonVariants({ className: 'place-self-center' })} href="/">
<VscArrowLeft size={20} /> Go back
</Link>
</div>

View File

@@ -1,8 +1,78 @@
'use client';
import { Analytics } from '@vercel/analytics/react';
import type { Metadata } from 'next';
import { Providers } from './providers';
import { DESCRIPTION } from '~/util/constants';
import { inter } from '~/util/fonts';
import '@unocss/reset/tailwind-compat.css';
import '~/styles/unocss.css';
import '~/styles/cmdk.css';
import '~/styles/main.css';
export const metadata: Metadata = {
title: 'discord.js',
description: DESCRIPTION,
viewport: {
minimumScale: 1,
initialScale: 1,
width: 'device-width',
},
icons: {
other: [
{
url: '/favicon-32x32.png',
sizes: '32x32',
type: 'image/png',
},
{
url: '/favicon-16x16.png',
sizes: '16x16',
type: 'image/png',
},
],
apple: [
'/apple-touch-icon.png',
{
url: '/safari-pinned-tab.svg',
rel: 'mask-icon',
},
],
},
manifest: '/site.webmanifest',
themeColor: [
{ media: '(prefers-color-scheme: light)', color: '#f1f3f5' },
{ media: '(prefers-color-scheme: dark)', color: '#1c1c1e' },
],
colorScheme: 'light dark',
appleWebApp: {
title: 'discord.js',
},
applicationName: 'discord.js',
openGraph: {
siteName: 'discord.js',
type: 'website',
title: 'discord.js',
description: DESCRIPTION,
images: 'https://discordjs.dev/api/open-graph.png',
},
twitter: {
card: 'summary_large_image',
creator: '@iCrawlToGo',
},
other: {
'msapplication-TileColor': '#1c1c1e',
},
};
export default function GlobalError({ error }: { error: Error }) {
console.error(error);
@@ -17,6 +87,7 @@ export default function GlobalError({ error }: { error: Error }) {
</div>
</main>
</Providers>
<Analytics />
</body>
</html>
);

View File

@@ -4,6 +4,7 @@ import Link from 'next/link';
import vercelLogo from '~/assets/powered-by-vercel.svg';
import { Banner } from '~/components/Banner';
import { InstallButton } from '~/components/InstallButton';
import { buttonVariants } from '~/styles/Button';
import { DESCRIPTION } from '~/util/constants';
export default function Page() {
@@ -12,27 +13,18 @@ export default function Page() {
<Banner />
<div className="mx-auto max-w-6xl flex flex-col place-items-center gap-24 px-8 pb-16 pt-12 lg:min-h-[calc(100vh_-_40px)] lg:place-content-center lg:py-10">
<div className="flex flex-col place-items-center gap-10 lg:flex-row lg:gap-6">
<div className="flex flex-col place-items-center gap-8 text-center">
<div className="flex flex-col place-items-center gap-10 text-center">
<h1 className="text-3xl font-black leading-tight sm:text-7xl sm:leading-tight">
The <span className="relative rounded bg-blurple px-3 py-1 text-white">most popular</span> way to build
Discord bots.
</h1>
<p className="my-6 leading-normal text-neutral-700 dark:text-neutral-300">{DESCRIPTION}</p>
<div className="flex flex-row gap-4">
<Link
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="/docs"
>
<Link className={buttonVariants()} href="/docs">
Docs
</Link>
{/* <Link
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"
>
Guide
</Link> */}
<a
className="h-11 flex flex-row transform-gpu cursor-pointer select-none appearance-none place-items-center gap-2 border border-light-900 rounded bg-white px-4 text-base font-semibold leading-none text-black no-underline outline-none transition duration-200 active:translate-y-px dark:border-dark-100 hover:border-black active:bg-light-300 dark:bg-dark-400 hover:bg-light-200 dark:text-white focus:ring focus:ring-width-2 focus:ring-blurple dark:active:bg-dark-200 dark:hover:bg-dark-300"
className={buttonVariants({ variant: 'secondary' })}
href="https://discordjs.guide"
rel="noopener noreferrer"
target="_blank"
@@ -40,7 +32,7 @@ export default function Page() {
Guide <FiExternalLink />
</a>
<a
className="h-11 flex flex-row transform-gpu cursor-pointer select-none appearance-none appearance-none place-items-center gap-2 border border-light-900 rounded bg-white px-4 text-base font-semibold leading-none text-black no-underline outline-none transition duration-200 active:translate-y-px dark:border-dark-100 hover:border-black active:bg-light-300 dark:bg-dark-400 hover:bg-light-200 dark:text-white focus:ring focus:ring-width-2 focus:ring-blurple dark:active:bg-dark-200 dark:hover:bg-dark-300"
className={buttonVariants({ variant: 'secondary' })}
href="https://github.com/discordjs/discord.js"
rel="external noopener noreferrer"
target="_blank"

View File

@@ -0,0 +1,37 @@
import type { ApiDocumentedItem } from '@microsoft/api-extractor-model';
import { ApiAbstractMixin, ApiProtectedMixin, ApiReadonlyMixin, ApiStaticMixin } from '@microsoft/api-extractor-model';
import type { PropsWithChildren } from 'react';
export enum BadgeColor {
Danger = 'bg-red-500',
Primary = 'bg-blurple',
Warning = 'bg-yellow-500',
}
export function Badge({ children, color = BadgeColor.Primary }: PropsWithChildren<{ color?: BadgeColor | undefined }>) {
return (
<span
className={`h-5 flex flex-row place-content-center place-items-center rounded-full px-3 text-center text-xs font-semibold uppercase text-white ${color}`}
>
{children}
</span>
);
}
export function Badges({ item }: { item: ApiDocumentedItem }) {
const isStatic = ApiStaticMixin.isBaseClassOf(item) && item.isStatic;
const isProtected = ApiProtectedMixin.isBaseClassOf(item) && item.isProtected;
const isReadonly = ApiReadonlyMixin.isBaseClassOf(item) && item.isReadonly;
const isAbstract = ApiAbstractMixin.isBaseClassOf(item) && item.isAbstract;
const isDeprecated = Boolean(item.tsdocComment?.deprecatedBlock);
return (
<div className="flex flex-row gap-1 md:ml-7">
{isDeprecated ? <Badge color={BadgeColor.Danger}>Deprecated</Badge> : null}
{isProtected ? <Badge>Protected</Badge> : null}
{isStatic ? <Badge>Static</Badge> : null}
{isAbstract ? <Badge>Abstract</Badge> : null}
{isReadonly ? <Badge>Readonly</Badge> : null}
</div>
);
}

View File

@@ -0,0 +1,28 @@
import type { ReactNode } from 'react';
import { Anchor } from './Anchor';
export interface CodeListingProps {
/**
* The value of this heading.
*/
children: ReactNode;
/**
* Additional class names to apply to the root element.
*/
className?: string | undefined;
/**
* The href of this heading.
*/
href?: string | undefined;
}
export function CodeHeading({ href, className, children }: CodeListingProps) {
return (
<div
className={`flex flex-row flex-wrap place-items-center gap-1 break-all font-mono text-lg font-bold ${className}`}
>
{href ? <Anchor href={href} /> : null}
{children}
</div>
);
}

View File

@@ -20,7 +20,7 @@ export interface ExcerptTextProps {
*/
export function ExcerptText({ model, excerpt }: ExcerptTextProps) {
return (
<>
<span>
{excerpt.spannedTokens.map((token, idx) => {
if (token.kind === ExcerptTokenKind.Reference) {
const source = token.canonicalReference?.source;
@@ -59,6 +59,6 @@ export function ExcerptText({ model, excerpt }: ExcerptTextProps) {
return token.text;
})}
</>
</span>
);
}

View File

@@ -4,6 +4,7 @@ import { FiCheck } from '@react-icons/all-files/fi/FiCheck';
import { FiCopy } from '@react-icons/all-files/fi/FiCopy';
import { useEffect, useState } from 'react';
import { useCopyToClipboard } from 'react-use';
import { buttonVariants } from '~/styles/Button';
export function InstallButton() {
const [interacted, setInteracted] = useState(false);
@@ -16,7 +17,7 @@ export function InstallButton() {
return (
<button
className="cursor-copy select-none bg-transparent px-4 py-2 text-sm text-dark-50 dark:text-light-900"
className={buttonVariants({ variant: 'secondary', className: 'cursor-copy font-mono' })}
onClick={() => {
setInteracted(true);
copyToClipboard('npm install discord.js');

View File

@@ -1,3 +0,0 @@
export function NameText({ name }: { name: string }) {
return <h4 className="break-all font-mono text-lg font-bold">{name}</h4>;
}

View File

@@ -1,24 +1,27 @@
import type { ApiParameterListMixin } from '@microsoft/api-extractor-model';
import type { ApiDocumentedItem, ApiParameterListMixin } from '@microsoft/api-extractor-model';
import { useMemo } from 'react';
import { ExcerptText } from './ExcerptText';
import { Table } from './Table';
import { TSDoc } from './documentation/tsdoc/TSDoc';
import { resolveParameters } from '~/util/model';
const columnStyles = {
Name: 'font-mono whitespace-nowrap',
Type: 'font-mono whitespace-pre-wrap break-normal',
};
export function ParameterTable({ item }: { item: ApiParameterListMixin }) {
export function ParameterTable({ item }: { item: ApiDocumentedItem & ApiParameterListMixin }) {
const params = resolveParameters(item);
const rows = useMemo(
() =>
item.parameters.map((param) => ({
params.map((param) => ({
Name: param.name,
Type: <ExcerptText excerpt={param.parameterTypeExcerpt} model={item.getAssociatedModel()!} />,
Optional: param.isOptional ? 'Yes' : 'No',
Description: param.tsdocParamBlock ? <TSDoc item={item} tsdoc={param.tsdocParamBlock.content} /> : 'None',
Description: param.description ? <TSDoc item={item} tsdoc={param.description} /> : 'None',
})),
[item],
[item, params],
);
return (

View File

@@ -5,71 +5,33 @@ import type {
ApiPropertySignature,
} from '@microsoft/api-extractor-model';
import type { PropsWithChildren } from 'react';
import { Anchor } from './Anchor';
import { Badges } from './Badges';
import { CodeHeading } from './CodeHeading';
import { ExcerptText } from './ExcerptText';
import { InheritanceText } from './InheritanceText';
import { TSDoc } from './documentation/tsdoc/TSDoc';
export enum PropertySeparatorType {
Type = ':',
Value = '=',
}
export function Property({
item,
children,
separator,
inheritedFrom,
}: PropsWithChildren<{
inheritedFrom?: (ApiDeclaredItem & ApiItemContainerMixin) | undefined;
item: ApiProperty | ApiPropertySignature;
separator?: PropertySeparatorType;
}>) {
const isDeprecated = Boolean(item.tsdocComment?.deprecatedBlock);
const hasSummary = Boolean(item.tsdocComment?.summarySection);
return (
<div className="flex flex-col scroll-mt-30 gap-4" id={item.displayName}>
<div className="flex flex-col gap-2 md:-ml-9">
{isDeprecated || item.isReadonly || item.isOptional || (item as ApiProperty).isStatic ? (
<div className="flex flex-row gap-1 md:ml-7">
{isDeprecated ? (
<div className="h-5 flex flex-row place-content-center place-items-center rounded-full bg-red-500 px-3 text-center text-xs font-semibold uppercase text-white">
Deprecated
</div>
) : null}
{(item as ApiProperty).isStatic ? (
<div className="h-5 flex flex-row place-content-center place-items-center rounded-full bg-blurple px-3 text-center text-xs font-semibold uppercase text-white">
Static
</div>
) : null}
{item.isReadonly ? (
<div className="h-5 flex flex-row place-content-center place-items-center rounded-full bg-blurple px-3 text-center text-xs font-semibold uppercase text-white">
Readonly
</div>
) : null}
{item.isOptional ? (
<div className="h-5 flex flex-row place-content-center place-items-center rounded-full bg-blurple px-3 text-center text-xs font-semibold uppercase text-white">
Optional
</div>
) : null}
</div>
) : null}
<div className="flex flex-row flex-wrap place-items-center gap-1">
<Anchor href={`#${item.displayName}`} />
<h4 className="break-all font-mono text-lg font-bold">
{item.displayName}
{item.isOptional ? '?' : ''}
</h4>
<Badges item={item} />
<CodeHeading href={`#${item.displayName}`}>
{`${item.displayName}${item.isOptional ? '?' : ''}`}
<span>:</span>
{item.propertyTypeExcerpt.text ? (
<>
<h4 className="font-mono text-lg font-bold">{separator}</h4>
<h4 className="break-all font-mono text-lg font-bold">
<ExcerptText excerpt={item.propertyTypeExcerpt} model={item.getAssociatedModel()!} />
</h4>
</>
<ExcerptText excerpt={item.propertyTypeExcerpt} model={item.getAssociatedModel()!} />
) : null}
</div>
</CodeHeading>
</div>
{hasSummary || inheritedFrom ? (
<div className="mb-4 flex flex-col gap-4">

View File

@@ -7,7 +7,7 @@ import type {
} from '@microsoft/api-extractor-model';
import { ApiItemKind } from '@microsoft/api-extractor-model';
import { Fragment, useMemo } from 'react';
import { Property, PropertySeparatorType } from './Property';
import { Property } from './Property';
import { resolveMembers } from '~/util/members';
export function isPropertyLike(item: ApiItem): item is ApiProperty | ApiPropertySignature {
@@ -25,7 +25,6 @@ export function PropertyList({ item }: { item: ApiItemContainerMixin }) {
<Property
inheritedFrom={prop.inherited as ApiDeclaredItem & ApiItemContainerMixin}
item={prop.item as ApiProperty}
separator={PropertySeparatorType.Type}
/>
<div className="border-t-2 border-light-900 dark:border-dark-100" />
</Fragment>

View File

@@ -38,7 +38,7 @@ export function Header({
{name}
</span>
{sourceURL ? (
<a className="text-blurple" href={sourceURL}>
<a className="text-blurple" href={sourceURL} rel="external noopener noreferrer" target="_blank">
<VscFileCode />
</a>
) : null}

View File

@@ -1,32 +0,0 @@
import type { ApiDeclaredItem, ApiItemContainerMixin, ApiTypeParameterListMixin } from '@microsoft/api-extractor-model';
import type { ReactNode } from 'react';
// import { Outline } from '../Outline';
import { SyntaxHighlighter } from '../SyntaxHighlighter';
import { Documentation } from './Documentation';
import { MethodsSection } from './section/MethodsSection';
import { PropertiesSection } from './section/PropertiesSection';
import { SummarySection } from './section/SummarySection';
import { TypeParameterSection } from './section/TypeParametersSection';
import { hasProperties, hasMethods /* , serializeMembers */ } from './util';
export function MemberContainerDocumentation({
item,
subheading,
}: {
item: ApiDeclaredItem & ApiItemContainerMixin & ApiTypeParameterListMixin;
subheading?: ReactNode;
}) {
return (
<Documentation>
{subheading}
{/* @ts-expect-error async component */}
<SyntaxHighlighter code={item.excerpt.text} />
<SummarySection item={item} />
{item.typeParameters.length ? <TypeParameterSection item={item} /> : null}
{hasProperties(item) ? <PropertiesSection item={item} /> : null}
{hasMethods(item) ? <MethodsSection item={item} /> : null}
{/* <Outline members={serializeMembers(item)} /> */}
</Documentation>
);
}

View File

@@ -2,23 +2,15 @@ import type { ApiConstructor } from '@microsoft/api-extractor-model';
import { VscSymbolMethod } from '@react-icons/all-files/vsc/VscSymbolMethod';
import { ParameterTable } from '../../ParameterTable';
import { TSDoc } from '../tsdoc/TSDoc';
import { parametersString } from '../util';
import { DocumentationSection } from './DocumentationSection';
function getShorthandName(ctor: ApiConstructor) {
return `constructor(${ctor.parameters.reduce((prev, cur, index) => {
if (index === 0) {
return `${prev}${cur.isOptional ? `${cur.name}?` : cur.name}`;
}
return `${prev}, ${cur.isOptional ? `${cur.name}?` : cur.name}`;
}, '')})`;
}
import { CodeHeading } from '~/components/CodeHeading';
export function ConstructorSection({ item }: { item: ApiConstructor }) {
return (
<DocumentationSection icon={<VscSymbolMethod size={20} />} padded title="Constructor">
<div className="flex flex-col gap-2">
<h4 className="break-all font-mono text-lg font-bold">{getShorthandName(item)}</h4>
<CodeHeading>{`constructor(${parametersString(item)})`}</CodeHeading>
{item.tsdocComment ? <TSDoc item={item} tsdoc={item.tsdocComment} /> : null}
<ParameterTable item={item} />
</div>

View File

@@ -1,9 +1,9 @@
import type { ApiParameterListMixin } from '@microsoft/api-extractor-model';
import type { ApiDocumentedItem, ApiParameterListMixin } from '@microsoft/api-extractor-model';
import { VscSymbolParameter } from '@react-icons/all-files/vsc/VscSymbolParameter';
import { ParameterTable } from '../../ParameterTable';
import { DocumentationSection } from './DocumentationSection';
export function ParameterSection({ item }: { item: ApiParameterListMixin }) {
export function ParameterSection({ item }: { item: ApiDocumentedItem & ApiParameterListMixin }) {
return (
<DocumentationSection icon={<VscSymbolParameter size={20} />} padded title="Parameters">
<ParameterTable item={item} />

View File

@@ -6,10 +6,13 @@ import type {
ApiMethodSignature,
ApiProperty,
ApiPropertySignature,
ApiDocumentedItem,
ApiParameterListMixin,
} from '@microsoft/api-extractor-model';
import type { TableOfContentsSerialized } from '../TableOfContentItems';
import { METHOD_SEPARATOR, OVERLOAD_SEPARATOR } from '~/util/constants';
import { resolveMembers } from '~/util/members';
import { resolveParameters } from '~/util/model';
export function hasProperties(item: ApiItemContainerMixin) {
return resolveMembers(item, memberPredicate).some(
@@ -56,3 +59,13 @@ export function serializeMembers(clazz: ApiItemContainerMixin): TableOfContentsS
}
});
}
export function parametersString(item: ApiDocumentedItem & ApiParameterListMixin) {
return resolveParameters(item).reduce((prev, cur, index) => {
if (index === 0) {
return `${prev}${cur.isOptional ? `${cur.name}?` : cur.name}`;
}
return `${prev}, ${cur.isOptional ? `${cur.name}?` : cur.name}`;
}, '');
}

View File

@@ -1,6 +1,7 @@
import type { ApiClass, ApiConstructor } from '@microsoft/api-extractor-model';
import { ApiItemKind } from '@microsoft/api-extractor-model';
// import { Outline } from '../Outline';
import { Badges } from '../Badges';
import { Documentation } from '../documentation/Documentation';
import { HierarchyText } from '../documentation/HierarchyText';
import { Members } from '../documentation/Members';
@@ -16,6 +17,7 @@ export function Class({ clazz }: { clazz: ApiClass }) {
return (
<Documentation>
<Badges item={clazz} />
<ObjectHeader item={clazz} />
<HierarchyText item={clazz} type="Extends" />
<HierarchyText item={clazz} type="Implements" />

View File

@@ -1,19 +1,18 @@
import type { ApiEnumMember } from '@microsoft/api-extractor-model';
import { Anchor } from '../../Anchor';
import { NameText } from '../../NameText';
import { SignatureText } from '../../SignatureText';
import { TSDoc } from '../../documentation/tsdoc/TSDoc';
import { CodeHeading } from '~/components/CodeHeading';
export function EnumMember({ member }: { member: ApiEnumMember }) {
return (
<div className="flex flex-col scroll-mt-30" id={member.displayName}>
<div className="flex flex-col gap-2 md:flex-row md:place-items-center md:-ml-8.5">
<Anchor href={`#${member.displayName}`} />
<NameText name={member.name} />
<CodeHeading className="md:-ml-8.5" href={`#${member.displayName}`}>
{member.name}
<span>=</span>
{member.initializerExcerpt ? (
<SignatureText excerpt={member.initializerExcerpt} model={member.getAssociatedModel()!} />
) : null}
</div>
</CodeHeading>
{member.tsdocComment ? <TSDoc item={member} tsdoc={member.tsdocComment.summarySection} /> : null}
</div>
);

View File

@@ -1,22 +1,11 @@
import type { ApiMethod, ApiMethodSignature } from '@microsoft/api-extractor-model';
import { ApiItemKind } from '@microsoft/api-extractor-model';
import { useMemo } from 'react';
import { Anchor } from '~/components/Anchor';
import { Badges } from '~/components/Badges';
import { CodeHeading } from '~/components/CodeHeading';
import { ExcerptText } from '~/components/ExcerptText';
function getShorthandName(method: ApiMethod | ApiMethodSignature) {
return `${method.name}${method.isOptional ? '?' : ''}(${method.parameters.reduce((prev, cur, index) => {
if (index === 0) {
return `${prev}${cur.isOptional ? `${cur.name}?` : cur.name}`;
}
return `${prev}, ${cur.isOptional ? `${cur.name}?` : cur.name}`;
}, '')})`;
}
import { parametersString } from '~/components/documentation/util';
export function MethodHeader({ method }: { method: ApiMethod | ApiMethodSignature }) {
const isDeprecated = Boolean(method.tsdocComment?.deprecatedBlock);
const key = useMemo(
() => `${method.displayName}${method.overloadIndex && method.overloadIndex > 1 ? `:${method.overloadIndex}` : ''}`,
[method.displayName, method.overloadIndex],
@@ -25,35 +14,12 @@ export function MethodHeader({ method }: { method: ApiMethod | ApiMethodSignatur
return (
<div className="flex flex-col scroll-mt-30" id={key}>
<div className="flex flex-col gap-2 md:-ml-9">
{isDeprecated ||
(method.kind === ApiItemKind.Method && (method as ApiMethod).isProtected) ||
(method.kind === ApiItemKind.Method && (method as ApiMethod).isStatic) ? (
<div className="flex flex-row gap-1 md:ml-7">
{isDeprecated ? (
<div className="h-5 flex flex-row place-content-center place-items-center rounded-full bg-red-500 px-3 text-center text-xs font-semibold uppercase text-white">
Deprecated
</div>
) : null}
{method.kind === ApiItemKind.Method && (method as ApiMethod).isProtected ? (
<div className="h-5 flex flex-row place-content-center place-items-center rounded-full bg-blurple px-3 text-center text-xs font-semibold uppercase text-white">
Protected
</div>
) : null}
{method.kind === ApiItemKind.Method && (method as ApiMethod).isStatic ? (
<div className="h-5 flex flex-row place-content-center place-items-center rounded-full bg-blurple px-3 text-center text-xs font-semibold uppercase text-white">
Static
</div>
) : null}
</div>
) : null}
<div className="flex flex-row flex-wrap place-items-center gap-1">
<Anchor href={`#${key}`} />
<h4 className="break-all font-mono text-lg font-bold">{getShorthandName(method)}</h4>
<h4 className="font-mono text-lg font-bold">:</h4>
<h4 className="break-all font-mono text-lg font-bold">
<ExcerptText excerpt={method.returnTypeExcerpt} model={method.getAssociatedModel()!} />
</h4>
</div>
<Badges item={method} />
<CodeHeading href={`#${key}`}>
{`${method.name}(${parametersString(method)})`}
<span>:</span>
<ExcerptText excerpt={method.returnTypeExcerpt} model={method.getAssociatedModel()!} />
</CodeHeading>
</div>
</div>
);

View File

@@ -0,0 +1,17 @@
import { cva } from 'class-variance-authority';
export const buttonVariants = cva(
'h-11 flex flex-row transform-gpu cursor-pointer select-none appearance-none place-items-center rounded 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 gap-2',
{
variants: {
variant: {
primary: 'bg-blurple text-white border-0',
secondary:
'bg-white text-gray-800 border-gray-400 border border-light-900 text-black transition duration-200 active:translate-y-px dark:border-dark-100 hover:border-black active:bg-light-300 dark:bg-dark-400 hover:bg-light-200 dark:text-white focus:ring focus:ring-width-2 focus:ring-blurple dark:active:bg-dark-200 dark:hover:bg-dark-300',
},
},
defaultVariants: {
variant: 'primary',
},
},
);

View File

@@ -12,7 +12,7 @@ export function resolveMembers<T extends ApiItem>(
) {
const seenItems = new Set<string>();
const inheritedMembers = parent.findMembersWithInheritance().items.reduce((acc, item) => {
if (predicate(item)) {
if (predicate(item) && !seenItems.has(item.displayName)) {
acc.push({
item,
inherited:
@@ -20,7 +20,8 @@ export function resolveMembers<T extends ApiItem>(
? undefined
: (item.parent as ApiItemContainerMixin | undefined),
});
seenItems.add(item.containerKey);
seenItems.add(item.displayName);
}
return acc;

View File

@@ -1,4 +1,11 @@
import type { ApiEntryPoint, ApiModel } from '@microsoft/api-extractor-model';
import type {
ApiDocumentedItem,
ApiEntryPoint,
ApiModel,
ApiParameterListMixin,
Excerpt,
} from '@microsoft/api-extractor-model';
import type { DocSection } from '@microsoft/tsdoc';
export function findMemberByKey(model: ApiModel, packageName: string, containerKey: string) {
const pkg = model.tryGetPackageByName(`@discordjs/${packageName}`)!;
@@ -13,3 +20,32 @@ export function findMember(model: ApiModel, packageName: string, memberName: str
const pkg = model.tryGetPackageByName(`@discordjs/${packageName}`)!;
return pkg.entryPoints[0]?.findMembersByName(memberName)[0];
}
interface ResolvedParameter {
description?: DocSection | undefined;
isOptional: boolean;
name: string;
parameterTypeExcerpt: Excerpt;
}
/**
* This takes an api item with a parameter list and resolves the names and descriptions of all the parameters.
*
* @remarks
* This is different from accessing `Parameter#name` or `Parameter.tsdocBlockComment` as this method cross-references the associated tsdoc
* parameter names and descriptions and uses them as a higher precedence to the source code.
* @param item - The api item to resolve parameter data for
* @returns An array of parameters
*/
export function resolveParameters(item: ApiDocumentedItem & ApiParameterListMixin): ResolvedParameter[] {
return item.parameters.map((param, idx) => {
const tsdocAnalog = item.tsdocComment?.params.blocks[idx];
return {
name: param.tsdocParamBlock?.parameterName ?? tsdocAnalog?.parameterName ?? param.name,
description: param.tsdocParamBlock?.content ?? tsdocAnalog?.content,
isOptional: param.isOptional,
parameterTypeExcerpt: param.parameterTypeExcerpt,
};
});
}

View File

@@ -53,17 +53,19 @@
"conventional-changelog-cli": "^2.2.2",
"husky": "^8.0.3",
"is-ci": "^3.0.1",
"lint-staged": "^13.2.1",
"lint-staged": "^13.2.2",
"tsup": "^6.7.0",
"turbo": "^1.9.1",
"turbo": "^1.9.3",
"typescript": "^5.0.4",
"unocss": "^0.51.4",
"vercel": "^28.18.5",
"unocss": "^0.51.8",
"vercel": "^29.0.3",
"vitest": "^0.29.8"
},
"resolutions": {
"@microsoft/tsdoc-config@~0.16.1": "patch:@microsoft/tsdoc-config@npm%3A0.16.2#./.yarn/patches/@microsoft-tsdoc-config-npm-0.16.2-30fd115d09.patch",
"@microsoft/tsdoc-config@0.16.2": "patch:@microsoft/tsdoc-config@npm%3A0.16.2#./.yarn/patches/@microsoft-tsdoc-config-npm-0.16.2-30fd115d09.patch"
"@microsoft/tsdoc-config@0.16.2": "patch:@microsoft/tsdoc-config@npm%3A0.16.2#./.yarn/patches/@microsoft-tsdoc-config-npm-0.16.2-30fd115d09.patch",
"yaml@^2.2.2": "patch:yaml@npm%3A2.2.2#./.yarn/patches/yaml-npm-2.2.2-6e3cddb343.patch",
"yaml@2.2.2": "patch:yaml@npm%3A2.2.2#./.yarn/patches/yaml-npm-2.2.2-6e3cddb343.patch"
},
"engines": {
"node": ">=16.9.0"

View File

@@ -21,6 +21,11 @@ describe('Format Tag', () => {
test('GIVEN tag with no prefix THEN return tag', () => {
expect(formatTag('13.5.1')).toEqual({ isSubpackage: false, package: 'discord.js', semver: '13.5.1' });
expect(formatTag('13.7.0')).toEqual({ isSubpackage: false, package: 'discord.js', semver: '13.7.0' });
expect(formatTag('create-discord-bot@1.0.0')).toEqual({
isSubpackage: false,
package: 'create-discord-bot',
semver: '1.0.0',
});
});
test('GIVEN no or invalid tag THEN return null', () => {

View File

@@ -10,6 +10,7 @@
"format": "prettier --write . && cross-env TIMING=1 eslint src __tests__ --ext .mjs,.js,.ts --fix --format=pretty",
"fmt": "yarn format"
},
"type": "module",
"main": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"directories": {
@@ -32,7 +33,8 @@
],
"repository": {
"type": "git",
"url": "https://github.com/discordjs/discord.js.git"
"url": "https://github.com/discordjs/discord.js.git",
"directory": "packages/actions"
},
"bugs": {
"url": "https://github.com/discordjs/discord.js/issues"
@@ -43,16 +45,16 @@
"@actions/glob": "^0.4.0",
"@planetscale/database": "^1.7.0",
"tslib": "^2.5.0",
"undici": "^5.21.2"
"undici": "^5.22.0"
},
"devDependencies": {
"@types/node": "16.18.23",
"@types/node": "16.18.25",
"@vitest/coverage-c8": "^0.30.1",
"cross-env": "^7.0.3",
"eslint": "^8.38.0",
"eslint": "^8.39.0",
"eslint-config-neon": "^0.1.42",
"eslint-formatter-pretty": "^5.0.0",
"prettier": "^2.8.7",
"prettier": "^2.8.8",
"tsup": "^6.7.0",
"typescript": "^5.0.4",
"vitest": "^0.29.8"

View File

@@ -5,10 +5,12 @@ inputs:
description: 'The input tag'
required: true
outputs:
subpackage:
description: 'Whether this tag is a subpackage tag'
package:
description: 'The package string that was extracted from this tag'
semver:
description: 'The semver string that was extracted from this tag'
runs:
using: node16
main: ../../dist/formatTag/index.mjs
main: ../../dist/formatTag/index.js

View File

@@ -1,12 +1,17 @@
export function formatTag(tag: string) {
// eslint-disable-next-line unicorn/no-unsafe-regex, prefer-named-capture-group
const parsed = /(^@.*\/(?<package>.*)@v?)?(?<semver>\d+.\d+.\d+)-?.*/.exec(tag);
// eslint-disable-next-line unicorn/no-unsafe-regex
const parsed = /(?:^@.*\/(?<package>.*)@v?)?(?<semver>\d+.\d+.\d+)-?.*/.exec(tag);
const parsedPackage = /(?<package>.*)@v?-?.*/.exec(tag);
if (parsed?.groups) {
const isSubpackage = typeof parsed.groups.package === 'string';
const pkg = isSubpackage ? parsed.groups.package : parsedPackage?.groups?.package ?? 'discord.js';
const semver = parsed.groups.semver;
return {
isSubpackage: typeof parsed.groups.package === 'string',
package: parsed.groups.package ?? 'discord.js',
semver: parsed.groups.semver,
isSubpackage,
package: pkg,
semver,
};
}

View File

@@ -3,9 +3,8 @@ description: 'Uploads the docs.api.json file to a planetscale database'
inputs:
package:
description: 'The package string'
required: true
version:
description: 'The semver string'
runs:
using: node16
main: ../../dist/uploadDocumentation/index.mjs
main: ../../dist/uploadDocumentation/index.js

View File

@@ -9,7 +9,7 @@ if (!process.env.DATABASE_URL) {
setFailed('DATABASE_URL is not set');
}
const pkg = getInput('package', { required: true });
const pkg = getInput('package') || '*';
const version = getInput('version') || 'main';
const sql = connect({
@@ -17,7 +17,7 @@ const sql = connect({
url: process.env.DATABASE_URL!,
});
const globber = await create(`docs/${pkg}/docs/docs.api.json`);
const globber = await create(`packages/${pkg}/docs/docs.api.json`);
for await (const file of globber.globGenerator()) {
const data = await readFile(file, 'utf8');
try {

View File

@@ -24,23 +24,24 @@
"license": "Apache-2.0",
"repository": {
"type": "git",
"url": "git+https://github.com/discordjs/discord.js.git"
"url": "https://github.com/discordjs/discord.js.git",
"directory": "packages/api-extractor-utils"
},
"bugs": {
"url": "https://github.com/discordjs/discord.js/issues"
},
"homepage": "https://discord.js.org",
"dependencies": {
"@microsoft/api-extractor-model": "7.26.4",
"@microsoft/api-extractor-model": "7.26.6",
"@microsoft/tsdoc": "0.14.2"
},
"devDependencies": {
"@types/node": "16.18.23",
"@types/node": "16.18.25",
"cross-env": "^7.0.3",
"eslint": "^8.38.0",
"eslint": "^8.39.0",
"eslint-config-neon": "^0.1.42",
"eslint-formatter-pretty": "^5.0.0",
"prettier": "^2.8.7",
"prettier": "^2.8.8",
"tsup": "^6.7.0",
"typescript": "^5.0.4"
},

View File

@@ -2,7 +2,7 @@ import type { ApiModel, ApiItem } from '@microsoft/api-extractor-model';
import type { DocBlock } from '@microsoft/tsdoc';
import { blockTag, type DocBlockTagJSON } from './CommentBlockTag.js';
import { type AnyDocNodeJSON, type DocNodeJSON, node } from './CommentNode.js';
import { createCommentNode } from '.';
import { createCommentNode } from './index.js';
export interface DocBlockJSON extends DocNodeJSON {
content: AnyDocNodeJSON[];

View File

@@ -1,7 +1,7 @@
import type { ApiItem, ApiModel } from '@microsoft/api-extractor-model';
import type { DocNodeContainer } from '@microsoft/tsdoc';
import { type AnyDocNodeJSON, type DocNodeJSON, node } from './CommentNode.js';
import { createCommentNode } from '.';
import { createCommentNode } from './index.js';
export interface DocNodeContainerJSON extends DocNodeJSON {
nodes: AnyDocNodeJSON[];

View File

@@ -2,7 +2,7 @@ import type { ApiItem, ApiModel } from '@microsoft/api-extractor-model';
import type { DocComment } from '@microsoft/tsdoc';
import { block, type DocBlockJSON } from './CommentBlock.js';
import { type DocNodeJSON, node } from './CommentNode.js';
import { createCommentNode } from '.';
import { createCommentNode } from './index.js';
export interface DocCommentJSON extends DocNodeJSON {
customBlocks: DocBlockJSON[];

View File

@@ -2,6 +2,17 @@
All notable changes to this project will be documented in this file.
# [@discordjs/brokers@0.2.1](https://github.com/discordjs/discord.js/compare/@discordjs/brokers@0.2.0...@discordjs/brokers@0.2.1) - (2023-05-01)
## Bug Fixes
- Fix external links (#9313) ([a7425c2](https://github.com/discordjs/discord.js/commit/a7425c29c4f23f1b31f4c6a463107ca9eb7fd7e2))
## Documentation
- Generate static imports for types with api-extractor ([98a76db](https://github.com/discordjs/discord.js/commit/98a76db482879f79d6bb2fb2e5fc65ac2c34e2d9))
- Use `@link` in `@see` (#9348) ([d66d113](https://github.com/discordjs/discord.js/commit/d66d1133331b81563588db4500c63a18c3c3dfae))
# [@discordjs/brokers@0.2.0](https://github.com/discordjs/discord.js/compare/@discordjs/brokers@0.1.0...@discordjs/brokers@0.2.0) - (2023-04-01)
## Bug Fixes

View File

@@ -0,0 +1,4 @@
{
"extends": "./api-extractor.json",
"mainEntryPointFilePath": "<projectFolder>/dist-docs/index.d.ts"
}

View File

@@ -1,6 +1,6 @@
{
"name": "@discordjs/brokers",
"version": "0.2.0",
"version": "0.2.1",
"description": "Powerful set of message brokers",
"scripts": {
"test": "vitest run",
@@ -9,7 +9,7 @@
"lint": "prettier --check . && cross-env TIMING=1 eslint src __tests__ --ext .mjs,.js,.ts --format=pretty",
"format": "prettier --write . && cross-env TIMING=1 eslint src __tests__ --ext .mjs,.js,.ts --fix --format=pretty",
"fmt": "yarn format",
"docs": "yarn build:docs && api-extractor run --local",
"docs": "yarn build:docs && api-extractor run --local && api-extractor run --local --config ./api-extractor-docs.json",
"prepack": "yarn lint && yarn test && yarn build",
"changelog": "git cliff --prepend ./CHANGELOG.md -u -c ./cliff.toml -r ../../ --include-path 'packages/brokers/*'",
"release": "cliff-jumper"
@@ -18,9 +18,9 @@
"module": "./dist/index.mjs",
"typings": "./dist/index.d.ts",
"exports": {
"types": "./dist/index.d.ts",
"import": "./dist/index.mjs",
"require": "./dist/index.js",
"types": "./dist/index.d.ts"
"require": "./dist/index.js"
},
"directories": {
"lib": "src",
@@ -50,7 +50,8 @@
],
"repository": {
"type": "git",
"url": "git+https://github.com/discordjs/discord.js.git"
"url": "https://github.com/discordjs/discord.js.git",
"directory": "packages/brokers"
},
"bugs": {
"url": "https://github.com/discordjs/discord.js/issues"
@@ -63,14 +64,14 @@
},
"devDependencies": {
"@favware/cliff-jumper": "^2.0.0",
"@microsoft/api-extractor": "^7.34.4",
"@types/node": "16.18.23",
"@microsoft/api-extractor": "^7.34.6",
"@types/node": "16.18.25",
"@vitest/coverage-c8": "^0.30.1",
"cross-env": "^7.0.3",
"eslint": "^8.38.0",
"eslint": "^8.39.0",
"eslint-config-neon": "^0.1.42",
"eslint-formatter-pretty": "^5.0.0",
"prettier": "^2.8.7",
"prettier": "^2.8.8",
"tsup": "^6.7.0",
"typescript": "^5.0.4",
"vitest": "^0.29.8"

View File

@@ -2,6 +2,21 @@
All notable changes to this project will be documented in this file.
# [@discordjs/builders@1.6.2](https://github.com/discordjs/discord.js/compare/@discordjs/builders@1.6.1...@discordjs/builders@1.6.2) - (2023-05-01)
## Bug Fixes
- **BaseSelectMenuBuilder:** Modify class to be `abstract` (#9358) ([ca4de2d](https://github.com/discordjs/discord.js/commit/ca4de2d9c6bc204e85d1b7eae7eabd23dbeb4475))
- Correct `@link` tags that involve parents (#9351) ([fbbce3e](https://github.com/discordjs/discord.js/commit/fbbce3eb4ba20bc0c4806ca2259d1f86001594be))
- Fix external links (#9313) ([a7425c2](https://github.com/discordjs/discord.js/commit/a7425c29c4f23f1b31f4c6a463107ca9eb7fd7e2))
## Documentation
- Reference package names properly (#9426) ([d6bca9b](https://github.com/discordjs/discord.js/commit/d6bca9bb4d976dc069a5039250db7d5b3e9142ef))
- Generate static imports for types with api-extractor ([98a76db](https://github.com/discordjs/discord.js/commit/98a76db482879f79d6bb2fb2e5fc65ac2c34e2d9))
- **builders:** Add some basic documentation (#9359) ([8073561](https://github.com/discordjs/discord.js/commit/8073561824f911d1a18d0b4f1de39f452bc69fa9))
- Use `@link` in `@see` (#9348) ([d66d113](https://github.com/discordjs/discord.js/commit/d66d1133331b81563588db4500c63a18c3c3dfae))
# [@discordjs/builders@1.6.0](https://github.com/discordjs/discord.js/compare/@discordjs/builders@1.5.0...@discordjs/builders@1.6.0) - (2023-04-01)
## Bug Fixes

View File

@@ -18,7 +18,7 @@
## About
`@discord.js/builders` is a utility package for easily building Discord API payloads.
`@discordjs/builders` is a utility package for easily building Discord API payloads.
## Installation

View File

@@ -101,6 +101,7 @@ describe('Button Components', () => {
button.toJSON();
}).toThrowError();
// @ts-expect-error: Invalid style
expect(() => buttonComponent().setStyle(24)).toThrowError();
expect(() => buttonComponent().setLabel(longStr)).toThrowError();
// @ts-expect-error: Invalid parameter for disabled

View File

@@ -240,8 +240,10 @@ describe('Slash Commands', () => {
});
test('GIVEN a builder with valid channel options and channel_types THEN does throw an error', () => {
// @ts-expect-error: Invalid channel type
expect(() => getBuilder().addChannelOption(getChannelOption().addChannelTypes(100))).toThrowError();
// @ts-expect-error: Invalid channel types
expect(() => getBuilder().addChannelOption(getChannelOption().addChannelTypes(100, 200))).toThrowError();
});

View File

@@ -0,0 +1,4 @@
{
"extends": "./api-extractor.json",
"mainEntryPointFilePath": "<projectFolder>/dist-docs/index.d.ts"
}

View File

@@ -1,6 +1,6 @@
{
"name": "@discordjs/builders",
"version": "1.6.1",
"version": "1.6.2",
"description": "A set of builders that you can use when creating your bot",
"scripts": {
"test": "vitest run",
@@ -9,7 +9,7 @@
"lint": "prettier --check . && cross-env TIMING=1 eslint src __tests__ --ext .mjs,.js,.ts --format=pretty",
"format": "prettier --write . && cross-env TIMING=1 eslint src __tests__ --ext .mjs,.js,.ts --fix --format=pretty",
"fmt": "yarn format",
"docs": "yarn build:docs && api-extractor run --local",
"docs": "yarn build:docs && api-extractor run --local && api-extractor run --local --config ./api-extractor-docs.json",
"prepack": "yarn lint && yarn test && yarn build",
"changelog": "git cliff --prepend ./CHANGELOG.md -u -c ./cliff.toml -r ../../ --include-path 'packages/builders/*'",
"release": "cliff-jumper"
@@ -18,9 +18,9 @@
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"exports": {
"types": "./dist/index.d.ts",
"import": "./dist/index.mjs",
"require": "./dist/index.js",
"types": "./dist/index.d.ts"
"require": "./dist/index.js"
},
"directories": {
"lib": "src",
@@ -48,7 +48,8 @@
],
"repository": {
"type": "git",
"url": "https://github.com/discordjs/discord.js.git"
"url": "https://github.com/discordjs/discord.js.git",
"directory": "packages/builders"
},
"bugs": {
"url": "https://github.com/discordjs/discord.js/issues"
@@ -58,23 +59,23 @@
"@discordjs/formatters": "workspace:^",
"@discordjs/util": "workspace:^",
"@sapphire/shapeshift": "^3.8.2",
"discord-api-types": "^0.37.38",
"discord-api-types": "^0.37.41",
"fast-deep-equal": "^3.1.3",
"ts-mixer": "^6.0.3",
"tslib": "^2.5.0"
},
"devDependencies": {
"@favware/cliff-jumper": "^2.0.0",
"@microsoft/api-extractor": "^7.34.4",
"@types/node": "16.18.23",
"@microsoft/api-extractor": "^7.34.6",
"@types/node": "16.18.25",
"@vitest/coverage-c8": "^0.30.1",
"cross-env": "^7.0.3",
"downlevel-dts": "^0.11.0",
"esbuild-plugin-version-injector": "^1.1.0",
"eslint": "^8.38.0",
"eslint": "^8.39.0",
"eslint-config-neon": "^0.1.42",
"eslint-formatter-pretty": "^5.0.0",
"prettier": "^2.8.7",
"prettier": "^2.8.8",
"tsup": "^6.7.0",
"typescript": "^5.0.4",
"vitest": "^0.29.8"

View File

@@ -2,6 +2,16 @@
All notable changes to this project will be documented in this file.
# [@discordjs/collection@1.5.1](https://github.com/discordjs/discord.js/compare/@discordjs/collection@1.5.0...@discordjs/collection@1.5.1) - (2023-05-01)
## Bug Fixes
- Fix external links (#9313) ([a7425c2](https://github.com/discordjs/discord.js/commit/a7425c29c4f23f1b31f4c6a463107ca9eb7fd7e2))
## Documentation
- Generate static imports for types with api-extractor ([98a76db](https://github.com/discordjs/discord.js/commit/98a76db482879f79d6bb2fb2e5fc65ac2c34e2d9))
# [@discordjs/collection@1.5.0](https://github.com/discordjs/discord.js/compare/@discordjs/collection@1.4.0...@discordjs/collection@1.5.0) - (2023-04-01)
## Bug Fixes

View File

@@ -0,0 +1,4 @@
{
"extends": "./api-extractor.json",
"mainEntryPointFilePath": "<projectFolder>/dist-docs/index.d.ts"
}

View File

@@ -1,6 +1,6 @@
{
"name": "@discordjs/collection",
"version": "1.5.0",
"version": "1.5.1",
"description": "Utility data structure used in discord.js",
"scripts": {
"test": "vitest run",
@@ -9,7 +9,7 @@
"lint": "prettier --check . && cross-env TIMING=1 eslint src __tests__ --ext .mjs,.js,.ts --format=pretty",
"format": "prettier --write . && cross-env TIMING=1 eslint src __tests__ --ext .mjs,.js,.ts --fix --format=pretty",
"fmt": "yarn format",
"docs": "yarn build:docs && api-extractor run --local",
"docs": "yarn build:docs && api-extractor run --local && api-extractor run --local --config ./api-extractor-docs.json",
"prepack": "yarn lint && yarn test && yarn build",
"changelog": "git cliff --prepend ./CHANGELOG.md -u -c ./cliff.toml -r ../../ --include-path 'packages/collection/*'",
"release": "cliff-jumper"
@@ -18,9 +18,9 @@
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"exports": {
"types": "./dist/index.d.ts",
"import": "./dist/index.mjs",
"require": "./dist/index.js",
"types": "./dist/index.d.ts"
"require": "./dist/index.js"
},
"directories": {
"lib": "src",
@@ -44,7 +44,8 @@
],
"repository": {
"type": "git",
"url": "git+https://github.com/discordjs/discord.js.git"
"url": "https://github.com/discordjs/discord.js.git",
"directory": "packages/collection"
},
"bugs": {
"url": "https://github.com/discordjs/discord.js/issues"
@@ -52,15 +53,15 @@
"homepage": "https://discord.js.org",
"devDependencies": {
"@favware/cliff-jumper": "^2.0.0",
"@microsoft/api-extractor": "^7.34.4",
"@types/node": "16.18.23",
"@microsoft/api-extractor": "^7.34.6",
"@types/node": "16.18.25",
"@vitest/coverage-c8": "^0.30.1",
"cross-env": "^7.0.3",
"esbuild-plugin-version-injector": "^1.1.0",
"eslint": "^8.38.0",
"eslint": "^8.39.0",
"eslint-config-neon": "^0.1.42",
"eslint-formatter-pretty": "^5.0.0",
"prettier": "^2.8.7",
"prettier": "^2.8.8",
"tsup": "^6.7.0",
"typescript": "^5.0.4",
"vitest": "^0.29.8"

View File

@@ -2,6 +2,18 @@
All notable changes to this project will be documented in this file.
# [@discordjs/core@0.5.1](https://github.com/discordjs/discord.js/compare/@discordjs/core@0.4.0...@discordjs/core@0.5.1) - (2023-04-16)
## Bug Fixes
- **interactions:** Make `data` parameter optional (#9379) ([66dc401](https://github.com/discordjs/discord.js/commit/66dc4014fe4553f1dd73aaa7c32fd83e10bde263))
- **core:** Support attachment editing on interactions (#9356) ([676307f](https://github.com/discordjs/discord.js/commit/676307ff5c6c4ef56a353b6fc74501a1080da869))
- **core:** Missed optional options (#9311) ([6912faa](https://github.com/discordjs/discord.js/commit/6912faa9b3852adbacc7d0b002aae81be041f529))
## Typings
- **ChannelsAPI:** Use correct type for `editMessage` (#9399) ([0a1701b](https://github.com/discordjs/discord.js/commit/0a1701b0463919a895c518e5daa9836760d9b6cf))
# [@discordjs/core@0.5.1](https://github.com/discordjs/discord.js/compare/@discordjs/core@0.5.0...@discordjs/core@0.5.1) - (2023-04-16)
## Bug Fixes

Some files were not shown because too many files have changed in this diff Show More